Multiple Choice Questions (MCQs) on Object-Oriented Programming (OOP) with Answers

Object-Oriented Programming (OOPs)

Object-Oriented Programming (OOPs) is a software programming approach that addresses the limitations of the procedural approach such as reusability and maintainability. OOPs is a methodology that designs an application using classes and objects.

Classes and Objects

In OOPs, a single unit that combines data and functions is called an object. The class is a blueprint used for creating objects. It describes the state or behavior of an object and can have attributes and methods.

  • Attributes: Class attributes are public variables within a class and can be accessed by creating an object of a class.
  • Methods: A method is a group of code that performs a specific action and runs only when called.

Object, Instance Member Variable, and Functions

An object is an instance of a class that contains an address and takes up memory space. Objects have states and behavior defined by their template definition. Instance member variables include attributes, data members, field, and properties. Instance member functions include methods, procedures, actions, operations, and services.

Four Pillars of OOPs

OOPs has four primary pillars:

  • Data Abstraction: Hides implementation details while presenting the features to the outside world, reducing code complexity, and exposing essential parts.
  • Inheritance: A mechanism used to derive a new class from an existing class.
  • Polymorphism: Provides the ability for an object to take many forms.
  • Encapsulation: Hides data for protection and groups data and functions into a single unit.

OOPs MCQs

N/A

Implicit Return Type of Constructor

In Java, a constructor is a special method that has the same name as the class and is used to initialize object's state. It is called automatically when an object is created using the new keyword.

The return type of a constructor is not explicitly mentioned in the code, as it is always the class object in which it is defined. Therefore, option B is correct: "A class object in which it is defined."

It's important to note that constructors do not have a return type of void, nor do they return any values. They simply initialize the object's state and can have parameters to accept initial values.

Object Creation with "new" Keyword

In object-oriented programming, an object is created by invoking a constructor method using the `new` keyword. The `new` keyword creates a new instance of a class and returns a reference to it.

The object is created during run-time, when the code is executed. This allows for dynamic allocation of memory and instantiation of objects based on user input or other programmatic conditions.

Therefore, the correct answer is: At run time.

Identifying Constructor Types

There are several types of constructors in object-oriented programming including the default constructor, parameterized constructor, and copy constructor. However, the friend constructor is not a type of constructor in C++.

// Example of default and parameterized constructor in C++

#include <iostream>
using namespace std;

class MyClass {
  public:
    int x;
    MyClass() { // Default constructor
      x = 0;
    }
    MyClass(int y) { // Parameterized constructor
      x = y;
    }
};

int main() {
  MyClass obj1; // Object created with default constructor
  MyClass obj2(5); // Object created with parameterized constructor
  cout << obj1.x << endl; // Outputs 0
  cout << obj2.x << endl; // Outputs 5
  return 0;
}

Identifying the Scope Resolution Operator in C++

In C++, the scope resolution operator is denoted by "::" and it is used to specify the context in which an identifier (such as a function or variable) will be used.

For example, if you have a class named "MyClass" with a member function named "myFunction", you can use the scope resolution operator to define the function outside of the class definition like this:

Code:

void MyClass::myFunction() {
// function code
}

In this case, "::" is used to indicate that "myFunction" is a member function of "MyClass".

Overall, the scope resolution operator is an important tool in C++ for managing namespaces and avoiding naming conflicts.

Identifying non-member functions in C++ Classes

In C++ programming language, a class is a user-defined data type that defines a blueprint for objects. A class may also contain member functions, which are functions that are defined inside the class and can be used by objects of that class. However, there are also non-member functions, which are functions that are not part of the class but can still access its private members.

Out of the options given, the correct answer is (A) Friend function. This is because a friend function is not a member of the class. A friend function is declared inside the class with the keyword "friend", but it is not a member function because it does not belong to the class and does not have the "this" pointer. It is, however, granted access to the private and protected members of the class.

The other options are all member functions. A static function is a member function that belongs to the class itself rather than any instance of the class. A virtual function is a member function that can be overridden in derived classes. A const function is a member function that does not modify the object on which it is called.


class MyClass {
private:
    int x;
protected:
    int y;
public:
    void memberFunction() {/*...*/} // member function
    static void staticFunction() {/*...*/} // member function
    virtual void virtualFunction() {/*...*/} // member function
    void constFunction() const {/*...*/} // const member function
    friend void friendFunction(MyClass obj); // non-member function
};

void friendFunction(MyClass obj) {
    obj.x = 1; // can access private members
    obj.y = 2; // can access protected members
}


Types of Constructors in C++

In C++, there are three types of constructors: default constructor, parameterized constructor, and copy constructor.

Default Constructor Parameters

In Java, a default constructor does not require any parameter. It is a constructor that is generated automatically by the compiler if no other constructor is defined in the class.

// Example of a default constructor public class Person { String name;

// Default constructor public Person() { name = "John Doe"; } }

Access Control in C++ Classes

In C++, the data members and member functions of a class are private by default. This means that they are accessible only within the class and not outside of it. To allow access to certain members from outside the class, we must use access specifiers, such as public, private, or protected.


class MyClass { 
private:
    int myPrivateMember;      //only accessible within the class 
public: 
    int myPublicMember;       //accessible outside the class 
}

In the above example, myPrivateMember can be accessed only within MyClass, while myPublicMember can be accessed from outside the class.

OOPS Pillars and Class Relationships

Base class and derived class relationships come under inheritance, which is one of the pillars of OOPS. Inheritance allows a derived class to inherit properties and methods of the base class and further customize them according to its own needs. This leads to code reusability and better organization of code. Polymorphism, encapsulation, and abstraction are the other pillars of OOPS that help in achieving better software design and development.

Inheritance of Functions in Object-Oriented Programming

In object-oriented programming, derived or child classes can inherit properties and methods from a parent or base class. However, whether functions can be inherited from the base class depends on the type of function.

// Example of an Animal class with a constructor and a method class Animal { constructor(name, species) { this.name = name; this.species = species; }

eat() { console.log(`${this.name} is eating.`); } }

// Example of a Dog class that inherits from the Animal class class Dog extends Animal { // This subclass can have additional properties or methods bark() { console.log(`${this.name} is barking.`); } }

const myDog = new Dog("Fido", "Labrador Retriever"); myDog.eat(); // Output: "Fido is eating." myDog.bark(); // Output: "Fido is barking."

In the example above, the

Animal

class has a constructor and a method

eat()

. The

Dog

class inherits the constructor and method from the

Animal

class, but it does not technically inherit the functions themselves. Rather, it has access to them through the inheritance of the class properties and methods.

Therefore, the answer to the question is:

Answer: D) None of the functions can be inherited from the base class.

Types of Inheritance

In object-oriented programming, inheritance is a mechanism that allows a new class to be based on an existing class. It provides a way to create a new class, which is a modified version of an existing class, and reuse the existing class code. There are three commonly recognized types of inheritance:

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multilevel Inheritance

The correct answer to the question is C. Distributed is not a type of inheritance.


class MyClass extends MyParentClass {
  // child class implementation
}

Explanation:

In C++, a class is a blueprint for creating objects. An object is an instance of the class, which means that it is a specific instance of the class that has data and functions associated with it. Therefore, option B is correct, which states that an object is an instance of the class. Options A, C, and D are incorrect because they define a function, a data type, and a syntax, respectively, which are all related to a class, but not to an object.

Explanation:

Reusability is the capability of a software component to be used in multiple systems without having to be rewritten. It is an important property as it saves time and effort by allowing code to be reused instead of being rewritten. Reusability also promotes consistency and reliability in software development. Among the given options, option B is the correct answer as reusability can help decrease the testing time, allowing developers to focus on other aspects of the software development process.

Identifying Non-Overloadable Operators

In C++, the dot operator (.) and the scope resolution operator (::) cannot be overloaded. However, the bit-wise right shift operator (>>) can be overloaded.


    // Example of an overloaded operator
    class MyClass {
        public:
            int operator+(int num) {
                return 100 + num;
            }
    };
    
    // Example of a non-overloadable operator
    int main() {
        MyClass obj;
        obj.+(10); // Error: Cannot overload the dot operator
        obj::func(); // Error: Cannot overload the scope resolution operator
        obj >> 2; // Valid: The right shift operator can be overloaded
        return 0;
    }

Understanding Ad-hoc Polymorphism in Programming

In computer programming, polymorphism refers to the ability of an object or function to take on different forms or types. Ad-hoc polymorphism specifically refers to a type of polymorphism achieved through the use of overloaded functions or operators.

When a function or operator is overloaded, it means that it has multiple definitions that can be called depending on the arguments passed to it. This allows the function or operator to work with different data types, making it more flexible and versatile.

The term "ad-hoc" refers to the fact that these multiple definitions are created specifically for the purpose of handling different types of data, rather than being part of a pre-defined hierarchy of classes.

For example, in C++, the addition operator (+) can be overloaded to work with both integers and floating-point numbers:


int add(int x, int y) {
    return x + y;
}

float add(float x, float y) {
    return x + y;
}

In this example, the add() function is overloaded to work with both integers and floating-point numbers, allowing it to be used in different contexts. This is an example of ad-hoc polymorphism in action.

Access Modifiers for Fields in C Structures

In C programming language, the fields in a structure are public by default. There are no keywords such as public, private, or protected in C for defining access modifiers for fields.

Determining the Existence of a Variable in Memory

The existence of a variable in memory is determined based on its storage class.

There are several storage classes available in C programming language:

  • Automatic
  • Register
  • Static
  • External

The storage class of a variable determines its scope and lifetime. The scope of a variable defines where it is accessible in the program, while the lifetime defines how long the variable remains in memory.

Therefore, option B is the correct answer: a variable that comes into existence in memory is determined by its storage class.

//Example of a variable declaration with a storage class
static int num = 10;


Identifying the Feature for Object Interaction

In object-oriented programming, message passing is the feature that allows one object to interact with another object. Therefore, the correct answer is A) Message passing.

Total Access Specifiers in C++ Object-Oriented Programming

In C++ Object-Oriented Programming, there are three access specifiers: private, public, and protected. These are used to determine the visibility and accessibility of the class members.

Private members can only be accessed within the class or by friend functions.

Public members can be accessed anywhere, even outside the class.

Protected members can be accessed within the class and its subclasses (derived classes).

Therefore, the correct answer is option C, which states that there are three total access specifiers in OOPS for C++.Polymorphism via Overloading in Java

Identifying the Correct Constructor in Object-Oriented Programming

In Object-Oriented Programming, a constructor is a special method used to initialize objects when they are created. It has the same name as its class and doesn't have any return type.

There are different types of constructors such as:

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor

To identify the correct constructor, we need to look for the following:

  • The constructor name must be the same as the class name
  • The constructor doesn't have any return type
  • The constructor may or may not have parameters

Based on the criteria above, the correct constructor is:

class_name()

This is a default constructor that takes no parameters. It initializes the object's member variables to their default values.

Accessing Data Members of a Class

In order to access the data members of a class, one can use either the dot or arrow operator, depending on the situation. Both operators allow access to the members of an object of a class.

The dot operator is used when accessing members of an object that is accessed directly. The arrow operator, on the other hand, is used when accessing members of an object that is accessed indirectly through a pointer.

Therefore, the correct option is C) Dot or arrow operator, as required.

Feature to Reduce Use of Nested Classes

Inheritance is a feature that can be used to reduce the use of nested classes.

The use of inheritance allows a class to inherit properties and methods from a parent class, instead of creating a nested class within another class. This can lead to cleaner and more organized code, making it easier to read and maintain in the long run.

// Example of inheritance in Java
public class ParentClass {
    // properties and methods of ParentClass
}

public class ChildClass extends ParentClass {
    // properties and methods of ChildClass, inherited from ParentClass
}


C++ Memory Deallocation with delete

In C++, the `delete` operator is used to free the memory allocated for an object.

Example:


int* ptr = new int;  // dynamic memory allocation
delete ptr;          // freeing memory allocated for the object

Here, `ptr` is a pointer to a dynamically allocated integer object. The `delete` operator frees the memory allocated to the object.

It's important to note that once an object is deleted, its memory is unallocated and cannot be accessed anymore.

Identifying Non-Properties of an Object

In JavaScript, objects are used to store collections of data as properties. These properties have values that can be of any data type, including objects. However, not everything in an object is a property. The non-properties of an object are:

  • Names: Although object properties have names, the names themselves are not properties.
  • Attributes: Object properties have attributes (e.g. writable, enumerable, configurable), but these attributes are not themselves properties.
  • Identity: An object's identity is distinct from its properties. Two objects can have the same properties, but they are not the same object.

Therefore, the correct option below that is not a property of the object is:

A) Names

are not a property of the object.

// Sample code:
// Create a person object with properties
let person = {
  name: 'John',
  age: 35,
  occupation: 'Developer'
};

// Names, attributes, and identity are not properties of the object
console.log(Object.getOwnPropertyNames(person)); // ['name', 'age', 'occupation']
console.log(Object.getOwnPropertyDescriptors(person)); // [{ name: { value: 'John', writable: true, enumerable: true, configurable: true }, age: { value: 35, writable: true, enumerable: true, configurable: true }, occupation: { value: 'Developer', writable: true, enumerable: true, configurable: true } }]
console.log(person === {name: 'John', age: 35, occupation: 'Developer'}); // false

Understanding single-level inheritance in object-oriented programming

In object-oriented programming, inheritance allows a class to inherit characteristics, properties, and methods of another class, called the base class or parent class.

Single-level inheritance is a type of inheritance where a derived class inherits properties and methods from only one base class.

In the case of single-level inheritance, the derived class supports runtime inheritance, which means that the inheritance relationship between the base and derived classes is established at runtime, rather than at compile-time.

Multiple inheritances, on the other hand, support inheritance from more than one base class, which can lead to conflicts and complexities in the code. Therefore, some programming languages, such as Java, only support single-level inheritance to maintain simplicity and reduce errors.

Where Are Objects Typically Allocated in Memory?

In general, memory is allocated for objects in RAM (Random Access Memory).

Explanation:

Encapsulation and Abstraction are two fundamental concepts of Object-Oriented Programming.

  • Encapsulation means the technique to hide internal complexities of an object from other objects. It is used to protect the data from outside the world.
  • Abstraction means the technique to hide the implementation details of an object from other objects. It is used to focus on what an object does, instead of how it does it.
  • Encapsulation is achieved by using access modifiers such as public, private, and protected to restrict access to the internal state of an object.
  • Abstraction is achieved through abstract classes and interfaces. Abstract classes have abstract methods that must be implemented in the derived classes, while interfaces have all the methods as abstract.
  • Hence, it can be concluded that encapsulation is related to binding and hiding data, while abstraction is related to hiding implementation details.

Therefore, option B is correct: Encapsulation and abstraction differ on the basis of binding and hiding.

Explanation:

Function overriding is a concept in object-oriented programming that allows a subclass to provide its implementation of a method that is already defined in its superclass. This way, the subclass can customize or extend the behavior of the superclass' method. This concept is an example of polymorphism, which means having many forms. With function overriding, a method can have different implementations in different classes of objects.

Option A, abstraction, is a concept that refers to creating simplified models or representations of complex systems. It is not directly related to function overriding.

Option B, encapsulation, is a concept that involves the hiding of implementation details of an object from the outside world. It is not directly related to function overriding.

Option D, inheritance, is a concept that allows a subclass to inherit the properties and methods of its superclass. Although function overriding is a special case of inheritance, it specifically pertains to the overriding of methods in a subclass and is not the only aspect of inheritance.

Instances of which class cannot be created?

The instances of an Abstract class cannot be created.

 
// Example of an abstract class with a method
abstract class Shape {
  abstract void draw(); // abstract method
}
 
// Example of a subclass that extends the abstract class
class Rectangle extends Shape {
  void draw() {
    // Implementation of draw method for rectangle
  }
}

//Trying to create an instance of an abstract class
Shape s = new Shape(); // This will result in an error

In the example above, an abstract class named "Shape" has a method "draw" which is left abstract and doesn't have an implementation. Since the class is abstract, it cannot be instantiated by using the "new" keyword. A subclass named "Rectangle" is created which extends "Shape" and provides the implementation of the draw() method.

Implementation of Abstraction using Encapsulation

In object-oriented programming, encapsulation refers to the mechanism of wrapping the data and methods inside a single unit. Encapsulation and abstraction are closely related concepts. Encapsulation is used to provide a higher level of data security and code reusability.

One of the key features of encapsulation is that it provides a mechanism for implementing abstraction. Abstraction is a concept where the user is presented with only essential information and the complexities of the implementation are hidden.

Encapsulation ensures that the internal details of an object are hidden from the outside world. By making the variables and methods of a class private or protected, the implementation details are hidden from the user. The user can only access the public methods provided by the object, which provide only essential information without revealing the internal details. This makes it easier to use and understand the object.

In summary, encapsulation provides a way to implement abstraction by hiding the details of the implementation from the user and presenting only essential information.

Explanation:

A virtual function is a member function in a base class that is declared using the `virtual` keyword. When a derived class inherits this base class, it can provide its own implementation of the virtual function. This allows the program to determine which implementation of the function to call at runtime based on the type of object being referred to. This is called Runtime Polymorphism, which is achieved using virtual functions. Therefore, the correct answer is D) Runtime polymorphism.

Where should virtual functions be defined?

Virtual functions should be defined in the base class.


    class Base {
        public:
            virtual void myFunction() {
                // code here
            }
    };
    
    class Derived : public Base {
        // code here
    };

In this example,

myFunction()

is defined in the

Base

class as a virtual function. It can be overridden in any derived classes, like

Derived

.

Virtual Functions Accessibility

According to the C++ programming language, virtual functions should be declared as public in order to allow them to be accessed by other parts of the program. This allows them to be overridden by derived classes, which is one of the main features of virtual functions.


class Base {
  public:
    virtual void myFunction() {
      // some code here
    }
};

class Derived : public Base {
  public:
    void myFunction() {
      // overridden code here
    }
};

In the example above, the "myFunction" virtual function is declared as public in the base class. This allows it to be accessed by derived classes, such as the "Derived" class, which is declared as a public subclass of "Base". This allows the "myFunction" function to be overridden by the derived class and execute its own code.

Explanation:

False is the correct answer. Constructor functions cannot be constant because they are responsible for creating and initializing objects of a class, and if the constructor is constant, it cannot modify the object's state during initialization.

Dynamic Memory Allocation in C

In C programming language, dynamic memory allocation refers to creating space for storing variable size data during program execution. This memory is allocated on runtime using library functions such as calloc() and malloc().

Both calloc() and malloc() are used for allocating memory dynamically in C, hence the correct answer is (C) - Both (a) and (b).

Function calloc() is used to allocate memory for an array of elements, and it initializes all bytes in the allocated space to zero. On the other hand, function malloc() is used to allocate memory for a single block of memory, but it does not initialize the allocated space.

In general, it is a good programming practice to use dynamic memory allocation when the exact size of memory required is unknown or may need to be adjusted during runtime.

Types of Polymorphism in C++

In C++, there are two types of polymorphism: Runtime Polymorphism and Compile-time Polymorphism. The correct answer is (B) 2.

Alternative Names for Generic Class

A generic class is also referred to as a template class.

// Example usage
template <typename T>
class MyClass {
   // class code here
};

Overloading Operators using Friend Function

In C++, operator overloading is a powerful feature that allows operators such as +, -, *, and / to be overloaded to work with user-defined data types.

When overloading operators, a friend function can be used to grant access to private data members of a class.

Out of the options given, the * operator can be overloaded using the friend function.

Therefore, the correct answer is C) * can be overloaded using the friend function.

Answer

The correct answer is True.

Objects cannot be passed as a function in most programming languages. Functions are a different type of data than objects, and cannot be used interchangeably.

Identifying a Pure Object-Oriented Programming Language

In the given options, the pure object-oriented programming language is:

 B) SmallTalk 

Explanation:

A pure object-oriented programming language implements all the concepts of object-oriented programming without any exception. SmallTalk is the only language among the given options that follows this principle.

Abstract Data Types

In computer science, an abstract data type (ADT) is a type of data structure that is defined by its behavior (semantics) from the point of view of a user, without considering its implementation. It is an abstraction of a data structure which provides only the interface to which a set of operations can be performed. The user does not need to know how the data is being stored and how the operations are being implemented.

Out of the given options, class is an abstract data type because it provides the structure and interface of objects, without defining their implementation. Double, int, and string are primitive data types that are implemented in the programming language and do not provide any abstraction.

 
// Example of a class in Python
class Circle:
  def __init__(self, radius):
    self.radius = radius

  def get_area(self):
    return 3.14 * self.radius**2
  
  def get_circumference(self):
    return 2 * 3.14 * self.radius


Number of Catch Blocks in a Try Block

In a single Try block, we can use as many catch blocks as per our needs. There is no fixed limit on the number of catch blocks we can use in a Try block.


try {
    // some code that may throw an exception
} catch (ExceptionType1 ex) {
    // catch block to handle ExceptionType1
} catch (ExceptionType2 ex) {
    // catch block to handle ExceptionType2
} catch (ExceptionType3 ex) {
    // catch block to handle ExceptionType3
}

In the above code example, we have used three different catch blocks for handling three different types of exceptions that may occur in the try block.

Types of Constructors in C++

In C++, constructors are special member functions that are executed when an object of a Class is created. They are used to initialize the object's data members. There are several types of constructors:

1. Default constructor<br>
2. Parameterized constructor<br>
3. Copy constructor

A default constructor is a constructor that doesn't have any parameters. A parameterized constructor, on the other hand, takes parameters that are used to initialize the object's data members. A copy constructor is used to create a new object that is a copy of an existing object. It takes an object of the same class as a parameter.

Note: There is no such thing as a "friend constructor".

Number of Instances of an Abstract Class

In Java, an abstract class is a class that cannot be instantiated on its own, but can only be inherited by its subclasses. Therefore, the correct answer is option A) - 0. We cannot create any instances of an abstract class.

Code:


//abstract class cannot be instantiated
abstract class MyClass{
    //fields and methods
}

//subclass that extends MyClass
class MySubclass extends MyClass{
    //fields and methods of MySubclass
}

Option Incompatibility with "Virtual"

Out of the given options, the one that cannot be used with the term "virtual" is the constructor.


virtual Constructor 

The above is incorrect syntax; constructors cannot be declared as virtual. In contrast, destructors, classes, and member functions can be virtual.

Identifying Inheritance Type in Code


class Door:
    def __init__(self, number, status):
        self.number = number
        self.status = status

class Security:
    def __init__(self):
        self.security_level = 0

    def access_level(self, level):
        self.security_level = level

class WoodenDoor(Door, Security):
    def __init__(self, number, status):
        Door.__init__(self, number, status)
        Security.__init__(self)

class ScreenDoor(Door, Security):
    def __init__(self, number, status):
        Door.__init__(self, number, status)
        Security.__init__(self)

The above code implements multiple inheritances. The classes

WoodenDoor

and

ScreenDoor

both inherit from the two parent classes

Door

and

Security

. Therefore, the inheritance type in the code is multiple inheritances.

Implementation of Late Binding using Virtual Functions in C++

Virtual functions are used in C++ to implement polymorphism, which allows objects of different classes to be treated as if they were objects of the same class. One of the features of virtual functions is late binding, also known as dynamic binding.

Late binding is the process of determining which function or method to call during runtime, rather than during compile time. This is useful because it allows the program to make decisions based on the actual object being used, rather than just its data type.

To implement late binding, we declare a function as virtual in a base class, and then override it in the derived classes. This tells the compiler to use the implementation of the function in the derived class, rather than the one in the base class.

Example Code:


class Shape {
public:
   virtual void draw() {
      // base implementation of draw function
   }
};

class Circle: public Shape {
public:
   void draw() {
      // implementation of draw function for Circle class
   }
};

class Square: public Shape {
public:
   void draw() {
      // implementation of draw function for Square class
   }
};

int main() {
   Shape* shape;
   Circle circle;
   Square square;

   // calling draw function for Circle object using a Shape pointer
   shape = &circle;
   shape->draw();

   // calling draw function for Square object using a Shape pointer
   shape = &square;
   shape->draw();

   return 0;
}

In the above code, the base class Shape has a virtual function draw() that is overridden in the Circle and Square classes. When we declare a Shape pointer and assign it to a Circle or Square object, then call the draw() function using that pointer, the actual implementation of the function used will be determined at runtime based on the object type.

What is cout?

In C++, cout is an object that represents the standard output stream, usually the console. It is used with the insertion operator (<<) to display output to the console.


  std::cout << "Hello world!";


Understanding Function Overloading

Function overloading can be described as ad-hoc polymorphism. This means that a function can have multiple forms, with different parameter types or order. Function overloading in C++ allows you to create multiple functions with the same name but with different parameters, making it possible to perform similar operations on different data types.

For example, we can define a function called calculateArea() that calculates the area of a circle and a rectangle. Both functions could have the same name, but take different parameters. When we call the calculateArea() function with a value, the correct version of the function will be called based on the argument type.

Overall, function overloading provides developers with a way to create more flexible and reusable code, allowing us to perform similar operations on different types of data.

Developer of Object-Oriented Programming

Alan Kay is the developer of Object-Oriented Programming.

 
// sample code demonstrating the use of Object-Oriented Programming
class Animal {
  constructor(name, species) {
    this.name = name;
    this.species = species;
  }
  
  greet() {
    console.log(`Hi, my name is ${this.name} and I am a ${this.species}.`);
  }
}

let cat = new Animal("Whiskers", "cat");
let dog = new Animal("Fido", "dog");

cat.greet(); // outputs "Hi, my name is Whiskers and I am a cat."
dog.greet(); // outputs "Hi, my name is Fido and I am a dog."


Identifying OOPS Concepts

In Object-Oriented Programming (OOPS), the following are four fundamental concepts:
A) Inheritance
B) Compilation
C) Polymorphism
D) Encapsulation
Out of these, B) Compilation is not a concept of OOPS.


// Example of Inheritance in OOPS
class Parent {
  // properties
}

class Child extends Parent {
  // properties and methods 
}

// Example of Polymorphism in OOPS
class Animal {
  void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  void animalSound() {
    System.out.println("The pig says: oink oink");
  }
}

class Dog extends Animal {
  void animalSound() {
    System.out.println("The dog says: woof woof");
  }
}

// Example of Encapsulation in OOPS
public class Person {
  private String name;

  public String getName() {
    return name;
  }

  public void setName(String newName) {
    this.name = newName;
  }
}

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.