Next-Gen App & Browser
Testing Cloud
Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles
Prepare for your OOPs interview with our comprehensive list of OOPs interview questions for freshers and experienced candidates.
OVERVIEW
OOPs interview questions and answers help you master the essential concepts and techniques around Object-Oriented Programming language. It can also help nail your next interview and land you a dream job role.
Note: We have compiled all OOPs Interview Questions for you in a template format. Check it out now!
Here are the OOPs interview questions and answers for freshers that cover the fundamental concepts of Object-Oriented Programming, such as inheritance, polymorphism, encapsulation, and abstraction.
Object-Oriented Programming is a programming paradigm that uses objects instead of functions and procedures. These objects are grouped into classes. OOPs incorporates real-world entities like inheritance, polymorphism, and encapsulation into programming, allowing for the integration of data and methods.
OOPs need to be used for several reasons:
This is a frequently asked OOPs interview question. Some major Object-Oriented Programming languages include:
The following are the main features of OOPs:
An object in Object-Oriented Programming is a fundamental unit representing real-world entities. It is an instance of a class, with memory allocated only upon instantiation (object creation). Objects possess identity, state, and behavior, containing data and code to manipulate it. Interaction between objects doesn't require knowledge of each other's data or code specifics, just the types of messages accepted and responses provided.
A class is a user-defined data type that consists of data members and member functions accessible through an instance of the class. It represents the common properties or methods of all objects of a specific type, functioning as a blueprint for an object.
This is one of the most commonly asked OOPs interview questions. Here are the differences between a class and a structure:
Feature | Class | Structure |
---|---|---|
Access Modifiers | Supports public, private, and protected access modifiers. | Typically only supports public access modifiers (implementation-dependent). |
Inheritance | Supports inheritance (single or multiple, depending on the language). | Does not support inheritance (except in C++, where it supports single inheritance). |
Constructor/Destructor | Has constructors and destructors. | Does not have constructors or destructors. |
Method Overloading | Supports method overloading. | Supports method overloading (implementation-dependent). |
Method Overriding | Supports method overriding (in case of inheritance). | Does not support method overriding. |
Default Members | Members are private by default (in most languages). | Members are public by default. |
Size | Can have a size larger than the sum of its members (due to additional metadata). | Size is equal to the sum of its members' sizes. |
Memory Allocation | Objects are typically allocated on the heap. | Structures are typically allocated on the stack or embedded in other data structures. |
Recommended Usage | Used for complex data types and to model real-world entities. | Used for simple, lightweight data types and grouping-related data. |
The primary differences between a class and an object in Object-Oriented Programming are:
Aspect | Class | Object |
---|---|---|
Definition | A class is a template or blueprint that defines the attributes and actions of objects. | An object is a specific instance of a class created from the class blueprint. |
Memory Allocation | A class itself does not occupy any memory space. | Objects occupy memory space when they are created. |
Creation | Classes are created by the programmer during the design phase. | Objects are created from classes at runtime, typically using constructors or object creation expressions. |
Properties and Methods | A class defines the properties and methods that objects will have. | An object has its own copies of the properties and can access and modify them. It also has access to the methods defined in the class. |
Instantiation | A class cannot be instantiated directly. | Objects can be instantiated from a class using the new keyword or object creation expressions. |
Purpose | A class serves as a blueprint or template. | Objects are the actual entities that exist and perform tasks during runtime. |
Access Modifiers | Classes can have access modifiers (public, private, protected) that control access to their members. | Objects do not have access modifiers; they access members based on the access modifiers defined in the class. |
Inheritance | Classes can inherit properties and methods from other classes through inheritance. | Objects cannot inherit directly from other objects but from the class they are instantiated from. |
Polymorphism | Classes support polymorphism, allowing objects of different classes to be treated as objects of a common superclass. | Objects can exhibit polymorphic behavior based on the class they are instantiated from. |
Among OOPs interview questions, this one is asked quite often. Some of the primary advantages of OOPs are as follows:
Here are the main differences between object-oriented and structured programming:
Aspect | Object-Oriented Programming | Structured Programming |
---|---|---|
Approach | OOPs focuses on creating objects that contain data and behavior. The program is organized around objects and their interactions. | Structured Programming focuses on writing a set of instructions or functions to perform tasks. The program is organized around procedures or functions. |
Data and Functions | In OOP, data and functions are combined into objects. Data is encapsulated within objects, and functions (methods) operate on that data. | In Structured Programming, data and functions are separate entities. Functions operate on data passed as arguments. |
Code Organization | Code is organized around classes and objects, promoting code reuse and modularity. | Code is organized around procedures or functions, often leading to monolithic and less modular code. |
Data Abstraction | OOPs supports data abstraction and encapsulation, where implementation details are hidden from the user. | Structured Programming has limited support for data abstraction and encapsulation. |
Inheritance | OOPs supports inheritance. | Structured Programming does not support inheritance. |
Polymorphism | OOPs supports polymorphism. | Structured Programming does not support polymorphism. |
Code Reuse | OOPs promotes code reuse through the inheritance and composition of objects. | Structured Programming has limited code reuse capabilities, often achieved through function libraries or modules. |
It's one of the go-to OOPs interview questions asked by interviewers. Programming paradigms categorize programming languages based on their core characteristics.
There are two main types:
These paradigms can be further subdivided:
The following are the differences between procedural programming and Object-Oriented Programming:
Aspect | Procedural Programming | Object-Oriented Programming |
---|---|---|
Data | Separate from procedures | Encapsulated within objects |
Program structure | Top-down approach | Divided into objects |
Data access | Usually global | Private (encapsulated) |
Code reusability | Limited, mainly through functions | High, through inheritance |
Data security | Less secure | More secure due to encapsulation |
Overloading | Generally not supported | Supports function and operator overloading |
Complexity | Simpler for small programs | Better for managing complex programs |
Modularity | Less modular | Highly modular |
Abstraction level | Low level of abstraction | High level of abstraction |
Inheritance | Not supported | Supported |
Polymorphism | Not supported | Supported |
Examples | C, Pascal | Java, C++, Python, C# |
Among all OOPs interview questions, this one is asked to assess your ability to use access specifiers.
As the name indicates, access specifiers are special types of keywords used to specify or control the accessibility of entities such as classes and methods.
The three primary access specifiers are:
When to use each:
Think of encapsulation like a capsule. You see a simple shell on the outside, but inside, it contains everything needed to do its job. In programming, encapsulation works similarly:
A typical OOPs interview question, this one is often asked. Abstraction in Object-Oriented Programming hides non-essential information and shows only what is necessary to users. This is key to representing real-world objects simply for easy user interaction.
There are two types of abstractions in Object-Oriented Programming:
In OOPs interview questions, this question tests your understanding of applying abstraction in your code. Here are a few best practices for using abstraction in your code:
Polymorphism is a core concept in Object-Oriented Programming that allows objects of various types to be treated in a uniform way. It makes code more flexible and reusable. It allows for writing methods that can work with objects of multiple types as long as they share a common superclass or interface.
For example, you could have a method that processes "Shape" objects, and it would work correctly whether you pass it a "Circle," "Square," or "Triangle" object, as long as they're all subclasses of "Shape."
This is one of the most commonly asked OOPs interview questions. There are two main types of polymorphism in Object-Oriented Programming:
As part of the OOPs interview questions, this one asks you to implement method overloading. When a class has multiple methods with the same name but different parameters, it is called method overloading.
Characteristics of method overloading:
Let’s understand this with an example in Java:
class Calculator {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public double add(double a, double b) {
return a + b;
}
}
When a subclass (child class) in Java implements a method that has the same name and parameters as a method in its parent class, this is called method overriding.
Characteristics of method overriding:
Let’s understand this with an example in Java:
class Shape {
double getArea() {
return 0;
}
}
class Circle extends Shape {
private double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double getArea() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private double width, height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
double getArea() {
return width * height;
}
}
public class Main {
public static void main(String[] args) {
Shape shape1 = new Circle(5);
Shape shape2 = new Rectangle(4, 6);
System.out.println("Circle area: " + shape1.getArea());
System.out.println("Rectangle area: " + shape2.getArea());
}
}
Among OOPs interview questions, this one targets the differences between overloading and overriding.
Aspect | Overloading | Overriding |
---|---|---|
Definition | Methods with identical names and differing parameters. | Implementing a method in a subclass that is already defined in its superclass. |
Purpose | Provides method implementation flexibility. | Allows subclasses to provide specific implementation. |
Class | Occurs within the same class or between parent and child classes. | Occurs between superclass and subclass. |
Method Signature | Must have different parameter types or a number of parameters. | Must have the same method signature (name and parameters). |
Return Type | Can be different | Must be the same or covariant |
Access Modifier | Can be different | Cannot be more restrictive in the subclass |
Static/Non-static | Can be either | Must be non-static |
Binding | Compile-time (static) binding | Runtime (dynamic) binding |
Here are the differences between compile-time polymorphism and runtime polymorphism:
Aspect | Compile-Time Polymorphism | Runtime Polymorphism |
---|---|---|
Resolution Time | Compile time | Runtime |
Also Known As | Static binding, early binding | Dynamic binding, late binding |
Implementation | Method overloading, operator overloading | Method overriding, Inheritance |
Flexibility | Less flexible | More flexible |
Performance | Generally faster | Slightly slower due to runtime resolution |
Decision Making | Before program execution | During program execution |
Type Checking | Done by compiler | Done at runtime |
No, runtime polymorphism cannot be achieved by data members in languages like Java or C++ because:
Inheritance in Object-Oriented Programming describes the ability of a class to inherit features from a superclass.
Syntax:
class SubClass extends SuperClass {
// SubClass members
}
Key elements of the syntax:
The superclass is the class that provides features inherited by a subclass, also known as the base class or parent class.
A subclass is a class that inherits all members (fields, methods, and nested classes) from another class, also known as a derived class, child class, or extended class.
This is a common OOPs interview question that is regularly asked. In Object-Oriented Programming, inheritance is categorized by the relationship between the derived class and its superclass.
Despite its strength in Object-Oriented Programming, inheritance does have its set of limitations:
Inheritance is an essential feature in Object-Oriented Programming languages like Java and C++.
Inheritance is like a parent passing traits to their child. In programming, it lets one class (the child) get all the characteristics and abilities of another class (the parent). This means the child class can use the parent's data and functions without rewriting them.
The main idea is to make new classes based on existing ones. The new class (child) gets everything from the old class (parent) and can add its unique features.
With inheritance, we'd save time writing the same code repeatedly for similar classes. It's like reinventing the wheel each time instead of just using a wheel that already exists.
Inheritance can be implemented by using:
No, you cannot declare abstract methods as static in Java due to the inherent contradictions between the concepts of abstract and static methods.
No, an abstract method cannot be private because it must be implemented in the child class.
Cohesion in OOPs refers to the degree to which the elements within a module or class belong together and work towards a single, well-defined purpose. It measures how closely related and focused the responsibilities of a single module or class are.
Data abstraction, the most basic form of abstraction in Object-Oriented Programming, involves manipulating complex objects where the underlying data structure or characteristics remain hidden.
This is among the most frequently asked OOPs interview questions. There are three main types of variables in Object-Oriented Programming:
There are two methods to implement abstraction in Java:
This is one of the most commonly asked OOPs interview questions. An abstract class is a template definition of methods and variables for a particular class or category of objects. In programming, objects are code units, and each object belongs to a generic class.
Abstract classes contain one or more abstract methods or behaviors. Abstracting objects or classes means summarizing their characteristics relevant to the current program's operation. Abstract classes are utilized in all Object-Oriented Programming languages, including Java, C++, C#, and VB.NET.
Below are some of the top OOPs interview questions for experienced professionals:
In Object-Oriented Programming, an interface is a contract that defines a set of abstract methods and constants that a class must implement. It serves as a blueprint for classes, specifying what methods should be available without dictating how these methods should be implemented.
Characteristics of interface include:
This is one of the frequently encountered OOPs interview questions. The reason is that abstract classes can contain non-final variables, while variables in an interface are final, public, and static.
interface SimpleInterface {
int CONSTANT = 100; // implicitly public, static, and final
}
abstract class SimpleAbstractClass {
int variable = 100; // can be non-final and instance-specific
}
The above example shows that interfaces can only have constants, while abstract classes can have mutable instance variables.
The following table demonstrates the difference between an abstract class and interface.
Characteristic | Abstract Class | Interface |
---|---|---|
Variables | Can have non-final instance variables. | Only constants (public static final). |
Methods | Can have both abstract and concrete methods. | All methods are implicitly abstract (before Java 8). |
Constructor | Can have constructors. | Cannot have constructors. |
Multiple Inheritance | A class can extend only one abstract class. | A class can implement multiple interfaces. |
Access Modifiers | Can use any access modifier for members. | All members are implicitly public. |
Instantiation | Cannot be instantiated. | Cannot be instantiated. |
Purpose | For objects that are closely related. | For unrelated classes to implement common behavior. |
Speed | Slightly faster | Slightly slower due to extra indirection. |
Default Method Implementation | Supported | Supported (from Java 8 onwards) |
Static Methods | Can have static methods | Can have static methods (from Java 8 onwards) |
Private Methods | Can have private methods | Can have private methods (from Java 9 onwards). |
No, you cannot declare an interface method as static in most Object-Oriented Programming languages, including Java and C#. Interface methods are, by default, abstract and public. Static methods belong to the class itself, not to any specific instance. The purpose of an interface is to define a contract that implementing classes must follow, which involves instance methods.
However, there are some exceptions:
No, constructors cannot be made static in most Object-Oriented Programming languages, including Java and C#.
Constructors are specifically designed to initialize new object instances when they are created. They set up the initial state of an object and are called automatically when an object is instantiated using the new keyword.
Static members, on the other hand, belong to the class itself rather than to any specific instance of the class. They can be accessed without creating an object of the class.
Making a constructor static would contradict its fundamental purpose of initializing individual object instances. It would also conflict with object creation and initialization in Object-Oriented Programming.
If you need class-level initialization, most languages provide other mechanisms like static initializer blocks or static methods that can be used for this purpose.
This is one of the OOPs interview questions that checks your understanding of creating a constructor. These are the rules to follow while creating constructors:
Declaring it as private would prevent it from being accessed and implemented outside the class.
In Object-Oriented Programming, such as C++, a virtual function or method is an inheritable and overridable function dispatched dynamically. Virtual functions play a crucial role in runtime polymorphism in OOPs, enabling the execution of target functions that are not precisely identified at compile time.
Many programming languages, including JavaScript, PHP, and Python, treat all methods as virtual by default and do not offer a modifier to alter this behavior. However, specific languages provide modifiers like final and private in Java and PHP to prevent methods from being overridden by derived classes.
Abstract classes in Object-Oriented Programming have several key characteristics:
This is one of the most commonly asked OOPs interview questions. Here are the differences between a copy constructor and an assignment operator:
Aspect | Copy Constructor | Assignment Operator |
---|---|---|
Purpose | Creates a new object as a copy of an existing one. | Copies contents of one object to an existing object. |
When it's called | When a new object is created. | When an existing object is assigned a new value. |
Syntax (C++) | ClassName(const ClassName& other) | ClassName& operator=(const ClassName& other) |
Returns | Nothing (constructs a new object). | Reference to the assigned object (usually). |
Self-assignment check | Not needed | Often needed to handle a = a case. |
Memory allocation | Always allocates new memory. | May or may not allocate new memory. |
Usage with new | Can be used with new. | Cannot be used with new. |
Inheritance behavior | Compiler-generated version is called the base class version. | Compiler-generated version doesn't call the base version. |
Default implementation | Performs shallow copy. | Performs shallow copy. |
Abstraction and encapsulation are important concepts in programming. They're related but serve different purposes:
The memory occupied by a class depends on several factors:
The actual memory usage can be larger than the sum of the sizes of data members due to:
This is one of the frequently asked OOPs interview questions. Coupling in Object-Oriented Programming refers to the degree of interdependence between classes or modules in a software system. It measures how closely connected or dependent different components are on each other.
There are two types of coupling:
Difference between tight coupling and loose coupling:
The operators that cannot be overloaded in C++ are:
This falls under the OOPs interview questions targeting the usage of manipulators. In Object-Oriented Programming, particularly in C++, manipulators are special functions or objects that modify input/output streams. They work by altering the formatting or behavior of streams without changing the actual data.
Manipulators work by modifying the state or behavior of input/output streams:
This is one of the OOPs interview questions that require explaining real-time examples of polymorphism. Let's consider a music player that can handle various types of audio files:
Each derived class inherits from AudioFile but implements the play() method differently due to the specific encoding and decoding requirements of each file format.
In the application:
//cpp
vector<AudioFile*> playlist;
playlist.push_back(new MP3File("Song1.mp3"));
playlist.push_back(new WAVFile("Song2.wav"));
playlist.push_back(new AADFile("Song3.aad"));
for (AudioFile* song : playlist) {
song->play(); // Polymorphic call
}
Here, the play() method is called on each song in the playlist. The actual implementation called depends on the specific file type, demonstrating polymorphism:
This example shows how polymorphism allows the application to treat different audio file types uniformly through a common interface (AudioFile) while executing the appropriate play() method for each specific file type.
Here are the differences between a base class and a superclass:
Aspect | Base Class | Superclass |
---|---|---|
Definition | The class from which other classes inherit. | The class from which other classes inherit. |
Usage | Commonly used in C++ terminology. | Commonly used in Java terminology. |
Synonyms | Parent class, superclass. | Parent class, base class. |
Hierarchy | At the top or intermediate level of inheritance. | At the top or intermediate level of inheritance |
Purpose | Provides common attributes and methods. | Provides common attributes and methods. |
Inheritance | Other classes derive from it. | Other classes extend from it. |
There are three main levels of data abstraction in OOP:
This is one of those OOPs interview questions that evaluate your practical use of overloading constructors.
Yes, it's possible to overload a constructor. You can define multiple constructors in the same class with different parameter lists. This allows objects to be created in different ways, providing flexibility in initialization.
Example:
public class Product {
String name;
double price;
int quantity;
// Default constructor
public Product() {
name = "Unknown";
price = 0.0;
quantity = 0;
}
// Constructor with name and price
public Product(String name, double price) {
this.name = name;
this.price = price;
this.quantity = 1; // default quantity
}
// Constructor with name, price, and quantity
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
public void display() {
System.out.println("Product: " + name + ", Price: $" + price + ", Quantity: " + quantity);
}
}
Usage:
public class Main {
public static void main(String[] args) {
Product p1 = new Product(); // default product
Product p2 = new Product("Laptop", 899.99); // product with name and price
Product p3 = new Product("Phone", 499.99, 3); // product with all details
p1.display();
p2.display();
p3.display();
}
}
Output:
Product: Unknown, Price: $0.0, Quantity: 0
Product: Laptop, Price: $899.99, Quantity: 1
Product: Phone, Price: $499.99, Quantity: 3
The above example shows how constructor overloading lets you create products with different levels of detail.
In Java, you can't truly overload the main() method in the sense of having multiple main() methods that the JVM will recognize as entry points for your program. However, you can have multiple methods named main() with different parameter lists within the same class. The JVM will only use the standard main(String[] args) as the entry point.
Here's an example to understand this:
public class MainOverloadExample {
// The actual entry point recognized by JVM
public static void main(String[] args) {
System.out.println("Main method called with String[] args");
// Calling other "main" methods
main();
main(5);
main("Hello");
}
// Overloaded main methods (not entry points)
public static void main() {
System.out.println("Main method with no arguments");
}
public static void main(int number) {
System.out.println("Main method with int argument: " + number);
}
public static void main(String str) {
System.out.println("Main method with String argument: " + str);
}
}
Important points to note:
Now that you've familiarized yourself with some of the most commonly asked OOPs interview questions and answers, it's essential to delve deeper into each of these concepts. This preparation will be instrumental in positioning yourself for success in OOPs-focused development roles.
Did you find this page helpful?