In today’s world, we do not have to worry about finding an approach to design software and maintaining its standard procedures and robustness. All thanks to object-oriented programming because it brings a structured approach to the coding industry and a revolution in programming techniques that we are familiar with. Without it, we cannot comprehend anything about a perfect solution to all basic limitations in programming. Hence, OOP is one of the subjects most frequently asked about in any coding interview.
In this article, we have discussed top OOP interview questions and answers with examples for 2024. You will get an idea about frequently asked OOP interview questions along with some advanced questions and problem-solving coding questions that will help you prepare for the interview.
It is a programming model based directly upon the concept of “objects”. Objects refer to anything you assume, like any certain object used in a game while conducting game development. For example, game characters and many other objects that repeat themselves. Hence, we can reuse those components again and again with a minimal amount of code. There are many OOP methods, such as reusability, abstraction, polymorphism, etc.
Feature | Object-Oriented Programming (OOP) | Structured Oriented Programming (SOP) |
Basic Concept | Based on objects and classes | Based on functions and procedures |
Modularity | High modularity with reusable objects | Functions/modules used for modularity |
Data Handling | Encapsulates data and functions together | Separates data and functions |
Focus | Focuses on data rather than procedures | Focuses on procedures and logic |
Inheritance | Supports inheritance to create new classes | Does not support inheritance |
Polymorphism | Supports polymorphism for method overloading | Does not support polymorphism |
Encapsulation | Strong encapsulation; data hiding is possible | Limited encapsulation; global variables used |
Reusability | High reusability of code through classes and objects | Moderate reusability through functions |
Complexity Management | Manages complexity through objects and interactions | Manages complexity through function calls |
Examples | Java, C++, Python, C# | C, Pascal, Fortran |
The super keyword is used to call the constructor method of the parent class from the base class. It is also used to refer to the methods of the parent class that are overridden in the base class.
A class in OOP can be represented as a blueprint for creating different objects. Those objects will further help in reusability and abstraction. An OOP class possesses different properties (attributes) and Behaviours (methods) that all the objects present in that class would have.
An object will act as an instance of a defined class. Hence object refers to any real-world entity and that entity will have its own properties and attributes. To create a complex system that has a huge amount of encapsulated data, objects play a very crucial role.
When there are many multiple objects or particularly multiple classes, then superclass and subclass help to define which property of other classes is inherited by our new class. A superclass (parent class) is a class that is extended or inherited by other classes. Hence, a superclass’s properties are shared by those other classes. While a subclass (child class) inherits different methods and attributes from its superclass, along with its own individual attributes.
Getters and setters are used to access and modify the private fields of a class, like private names, data types, values, or any kind of attributes. Getters try to retrieve the value of a field while setters update those values.
Here is a C++ code to understand more about how they are used:
class Person {
private:
string name;
int age;
public:
string getName() {
return name;
}
void setName(string newName) {
name = newName;
}
};
There are several types of variables in OOP which can be categorised on their scope and lifetime:
Feature | Class | Structure |
Keyword | Defined using the class keyword | Defined using the struct keyword |
Default Access | Members are private by default | Members are public by default |
Inheritance | Supports public, protected, and private | Supports only public inheritance |
Member Functions | Can have member functions | Can have member functions |
Constructor | Can have constructors and destructors | Can have constructors and destructors |
Memory Allocation | Allocates memory using the new keyword | Allocates memory using malloc or as a value |
Usage | Typically used for complex data structures | Typically used for simple data structures |
Feature | Class | Method | Object |
Definition | Blueprint for creating objects | A function that belongs to a class | An instance of a class |
Usage | Used to create objects | Used to define behaviours of a class | Represents a specific instance of a class |
Members | Contains data members and methods | Contains code that performs a specific task | N/A (Similar to a variable in non-OOP terms) |
Creation | Must be defined before creating objects | Part of a class, instantiated with objects | Created from a class using constructors |
Relationship | Multiple objects can be created from a class | Methods are part of a class | An object is an instance of a class |
Example | class Car { … }; | void Drive { … }; | Car myCar; |
Feature | Multiple Inheritance | Multilevel Inheritance | |
Number of Classes | A class can inherit from multiple base classes | A class inherits from a class, which inherits from another class | |
Complexity | This can lead to complex class hierarchies | Generally simpler and easier to understand | Example | class Derived : public Base1, public Base2 { } | class A { }; class B : public A { }; class C : public B { };
Feature | Overloading | Overriding | |
Definition | Multiple methods in the same class with the same name but different parameters | Replacing a method in a superclass with a method in a subclass with the same name and parameters | |
Occurrence | Within the same class | Between a superclass and its subclass | |
Inheritance | Not related to inheritance | Specifically related to inheritance | |
Usage | Enhances code readability and reduces method name clutter | Allows a subclass to provide a specific implementation of a method that is already provided by its superclass | Example | void print(int a); void print(double b) class Animal { void makeSound() { … } };
Access Modifier | Visibility | Accessibility | Inheritance |
Public | It can be accessed from anywhere, both within and outside the class, by any other class. | Yes | Yes |
Private | It can only be accessed from within the same class. | No | No |
Protected | It can be accessed from within the same class, subclasses, and classes in the same package. | Yes | Yes |
Feature | Abstract Class | Interface |
Definition | Can have both abstract and concrete methods | Can only have abstract methods |
Multiple | Cannot implement multiple inheritance | Can implement multiple inheritance |
Variables | Can have instance variables | Cannot have instance variables |
Implementation | Can provide a partial implementation of methods | Cannot provide an implementation of methods |
Constructor | Can have a constructor | Cannot have a constructor |
Final Variables | Can have final variables | Cannot have final variables |
Usage | Used to define a base class for other classes | Used to define a contract for implementing classes |
Feature | Data Abstraction | Encapsulation |
Definition | The process of hiding the complex implementation details and showing only the essential features of an object. | The bundling of data (attributes) and the methods (functions) that operate on the data into a single unit or class. |
Focus | Focuses on hiding the implementation complexity and showing only relevant information. | Focuses on bundling the data and methods that operate on the data together. |
Usage | Achieved through abstract classes and interfaces in OOP. | Achieved by using access modifiers (public, private, protected) in OOP. |
Purpose | Helps in reducing programming complexity and effort. | Helps in achieving data hiding and preventing direct access to data. |
Design patterns are important in providing proven solutions to common design problems in software development. There are many different specific design patterns that use OOP concepts like reusability, maintainability, scalability, etc., while also improving the quality and efficiency of the overall software program.
Cohesion refers to the measurement of how focused and tightly related responsibilities of a single module or class are. High cohesion means that the object class or particular module has only one dedicated task, while low cohesion means there are multiple unrelated tasks/responsibilities of that class.
The two main types of polymorphism are:
LSP states that the objects of a superclass must be replaceable with the objects of its subclasses, and it should not affect the correctness of the program. Hence a subclass should be able to substitute for its superclass without changing the overall behaviour of the program.
It is closely related to inheritance and polymorphism because, in inheritance, a new class (subclass) is created from the existing superclass, and on the other hand, polymorphism allows different class objects to be treated as a common superclass. LSP ensures that subclasses adhere to superclasses by enabling polymorphic substitution, creating a strong relationship between classes in an inheritance hierarchy.
The memory occupied depends on the size of its instance variables, methods and any additional functions in inheritance. Moreover, the exact memory usage by a class can vary based on the compilers used and the programming language itself.
Advantages | Disadvantages |
Modularity | Complexity |
Reusability | Difficulty |
Flexibility | Efficiency |
Productivity | Cost |
Maintainability | Learning Curve |
A special type of method in a class that can be automatically called during object creation is called a constructor. There are many types of constructors, such as parameterised constructors, copy constructors, default constructors, and constructor overloading.
On the other hand, a destructor is a method that is called when the object has gone out of scope or completely destroyed. Hence it is used to free resources, like memory or file handles. Generally, there is only one type of destructor. However, in some languages like C++, the concept of “virtual destructor” exists.
Yes, this can be done in many languages, like C++ and Java. In Java, overloading constructors is done to create objects with different initialisations or behaviours. But Java does not have destructors in the same manner as C++, as Java has automatic garbage collection.
In C++, constructor overloading allows the creation of objects in different initialisations, along with overloading destructors. Destructor overloading is not recommended due to the automatic and volatile nature of destructor calls.
A pure virtual function is declared in a base class but has zero implementation. It can be done using the ‘virtual’ keyword and assigning the value 0 to it. Classes that contain pure virtual functions are abstract classes and cannot be instantiated. Hence, subclasses must override pure virtual functions to provide implementations.
Shallow copy is used to copy the reference to objects so that objects are not duplicated by themselves. A deep copy creates a new copy of the object itself and all its elements. We can use shallow copy when we want to duplicate an object’s references. Using deep copy signifies complete duplication of an object along with its elements.
It is generally used to refer to the current object instance, primarily to access the method or variable of the current object and also to showcase the difference between class attributes and method parameters with the same name.
Program:
#include <iostream>
using namespace std;
class AbstractClass {
public:
virtual void abstractMethod() = 0; // Pure virtual function
};
class ConcreteClass : public AbstractClass {
public:
void abstractMethod() {
cout << “Implementation of abstractMethod” << endl;
}
};
int main() {
ConcreteClass obj;
obj.abstractMethod();
return 0;
}
Program:
class Engine:
def start(self):
print(“Engine started”)
def stop(self):
print(“Engine stopped”)
class Car:
def __init__(self):
self.engine = Engine()
def start(self):
print(“Car starting…”)
self.engine.start()
def stop(self):
print(“Car stopping…”)
self.engine.stop()
# Create a Car instance
car = Car()
# Use the Car’s start and stop methods
car.start()
car.stop()
Solution Program:
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
Question Program:
class Animal {
public void makeSound() {
System.out.println(“Animal makes a sound”);
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println(“Dog barks”);
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.makeSound();
}
}
Output: Dog Barks
Explanation: The ‘makeSound’ method of the ‘Dog’ class overrides the method of the ‘Animal’ class, invoking the method of the ‘Dog’ class due to dynamic method dispatch – a feature of polymorphism.
You can give one real-life scenario by taking the example of the car dashboard. In that, the dashboard shows essential info like fuel, speed, and temperature without revealing complex internal mechanisms. The driver interacts easily with simplified controls, allowing users to operate the vehicle without needing to understand its inner workings. Hence abstracting away the complex internal functions, which are time-consuming and difficult to understand.
Yes, you can run a Java application by using procedural programming. Java supports procedural code, which allows the use of static methods and variables within a single class containing the ‘main’ method.
To do this, first find the areas with tightly coupled code, which is unstructured and may contain possible errors. Design patterns like Singleton for shared resources can be used. Along with it, design patterns like Factory for object creation, Strategy for interchangeable behaviours, etc., can be done.
By using a design pattern, you can get information about the maintainable and scalable code, commonly changing code, which may contain possible problems. However, changing it can also introduce more complexity to the project, especially when the code is not properly understood.
Not using a design pattern can also result in ad-hoc solutions that are even harder to maintain and extend in long-term projects.
Aspect | Structural Design Patterns | Creational Design Patterns | Behavioural Design Patterns |
Purpose | Concerned with object composition and class structure. | Concerned with the process of object creation. | Concerned with object interaction and responsibility. |
Intent | Focuses on how classes and objects are composed to form larger structures. | Focuses on providing mechanisms for creating objects in a manner suitable to the situation. | Focuses on the interaction between objects and how they operate together in a system. |
Examples | Adapter, Composite, Decorator | Singleton, Factory Method, Builder | Observer, Strategy, Template Method |
Use Cases | When you want to simplify the structure of a system. | When you want to control the instantiation process, ensure consistency and flexibility. | When you want to define how objects interact in a system without specifying their concrete classes. |
A final block is used in Java within a try-catch-finally statement to always execute the code without any errors. Whenever any error comes, code is executed regardless if it throws out an exception or not.
To handle situations like this, you can consider the following approaches:
Here to ensure that a singleton class is thread-safe, you can take the help of synchronisation techniques like the double-checked locking or synchronised method to control access to the instance creation method.
Aspect | Error | Exception |
Definition | An Error indicates serious problems that a reasonable application should not try to catch. | An Exception indicates conditions that a reasonable application might want to catch. |
Handling | Errors are typically not caught or handled by the application. | Exceptions are meant to be caught and handled by the application. |
Types | Examples include OutOfMemoryError and StackOverflowError. | Examples include NullPointerException and IOException. |
Causes | Typically caused by the environment or virtual machine, not by the application’s code. | Typically, this is caused by the application’s code, such as invalid user input or resource unavailability. |
Impact | Errors are typically unrecoverable and may lead to the termination of the application. | Exceptions can often be handled gracefully, allowing the application to continue execution. |
It is used to handle exceptions in Java. The code which possibly throws an exception is placed in the try block, and the catch block is used to output the exception if it occurs.
Program:
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println(“An error occurred: ” + e.getMessage());
}
The following can be the limitations of OOP:
Aspect | Checked Exceptions | Unchecked Exceptions |
Definition | Must be caught or declared in the method signature. | It can be caught or not caught without requiring a catch or throws clause. |
Examples | IOException, ClassNotFoundException | NullPointerException, ArrayIndexOutOfBoundsException |
Handling | It must be handled using the try-catch or throws keyword. | Optional to handle; can be handled but not required. |
Impact | Checked at compile-time; helps in ensuring proper exception handling. | It is not checked at compile-time; it can lead to runtime exceptions if not handled properly. |
Purpose | Used for recoverable conditions that a method should anticipate and handle. | Typically used for programming errors or conditions that should not occur during normal operation. |
Yes, some of the limitations are:
In conclusion, these interview questions will help you find out the true nature of interview rounds and what type of questions can be asked. Preparation in each sub-field is necessary to easily answer all the interview questions.
Book a free counselling session
Get a personalized career roadmap
Get tailored program recommendations
Explore industry trends and job opportunities
Programs tailored for your Success
Popular
Data Science
Technology
Finance
Management
Future Tech
© 2024 Hero Vired. All rights reserved