Commonly Asked OOP Interview Questions

Usman Siddiqui
13 min readMay 31, 2021

Q. What is Object Oriented Programming?

Object-Oriented Programming refers to the programming paradigm defined using objects instead of only functions and methods. The objects contain data, called fields or attributes, and methods that provide the logic or supporting code. It provides capabilities such as inheritance, polymorphism, encapsulation and abstraction.

Q. What are the main features of Object Oriented Programming?

There are four main features of Object Oriented Programming.

  1. Encapsulation
  2. Abstraction
  3. Inheritance
  4. Polymorphism

Q. What is the difference between Imperative Programming and Declarative Programming?

  1. Imperative Programming is a programming paradigm that uses statements that change a program states.
  2. Declarative Programming is a programming paradigm that expresses the logic of computation without describing its control flow.

Suppose we have to write a program to get odd numbers from a collection and add those odd numbers into a separate list.

List<int> collection = new List<int> { 1, 2, 3, 4, 5 };

With Imperative Programming, we will describe the control flow that will save odd numbers from the collection into the list.

List<int> results = new List<int>();
foreach(var num in collection)
{
if (num % 2 != 0)
results.Add(num);
}

On the other hand, with declarative programming, you can write a code that describes what you want but not necessarily how to get it i.e. declare the desired results but not step by step.

var results = collection.Where( num => num % 2 != 0);-

Q. What is the difference between object oriented programming and procedural programming?

  1. Procedural Programming specifies the steps a program must take to reach the desired state, usually read in order from top to bottom.
  2. Object Oriented Programming organizes programs as objects, that contain some data and have some behavior. It usually follows bottom to top approach.

Q. What are the advantages of using OOPs?

  1. OOPs is very helpful in solving very complex level of problems.
  2. Highly complex programs can be created, handled, and maintained easily using object-oriented programming.
  3. OOPs promote code reuse, thereby reducing redundancy through inheritance.
  4. OOPs also helps to hide unnecessary details with the help of Data Abstraction.
  5. OOPs, are based on a bottom-up approach, unlike the Structural programming paradigm, which uses a top-down approach.
  6. Polymorphism offers a lot of flexibility in OOPs.

Q. What is a class?

A class can be understood as a template or a blueprint, which contains some values, known as member data or member, and some set of rules, known as behaviors or functions. So when an object is created, it automatically takes the data and functions that are defined in the class.
Therefore the class is basically a template or blueprint for objects. Also one can create as many objects as they want based on a class.

Q. What is an object?

An object refers to the instance of the class, which contains the instance of the members and behaviors defined in the class template. In the real world, an object is an actual entity to which a user interacts, whereas class is just the blueprint for that object. So the objects consume memory and have some characteristic behavior.

Q. What is encapsulation?

Encapsulation is the packing of data and functions operating on that data into a single component and restricting access to some of the object’s components.
Encapsulation means that the internal representation of an object is generally hidden from view outside of the object’s definition.

Encapsulation can also be defined in two different ways:

  1. Data hiding: Encapsulation is the process of hiding unwanted information, such as restricting access to any member of an object.
  2. Data binding: Encapsulation is the process of binding the data members and the methods together as a whole, as a class.
public class MyClass{public static void main(String []args){
Student student = new Student();

//Setting values of the variables
student.setName("usman");
student.setAge(24)

//Getting values of the variables
System.out.println(student.getName())
System.out.println(student.getAge())

// Direct access to the variables is not possible
// due to encapsulation
}
}
public class Student{
private String name;
private int age;

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

public String getName(){
return name;
}

public void setAge(int age){
this.age = age;
}

public int getAge(){
return age;
}
}

Q. What is abstraction?

Abstraction is a mechanism that represents the essential features without including implementation details. The main purpose of abstraction is to hide unnecessary details from the users.

public class MyClass{public static void main(String []args){
Circle circle = new Circle(4);

double area = circle.area();
System.out.println("Area is " + area);
// Implementation of method area is hidden from the client

}
}
class Circle {

private int radius;

public Circle(int radius){
this.radius = radius;
}

public double area(){
return Math.PI * Math.pow(radius, 2);
}
}

Q. What is the difference between abstraction and encapsulation?

Q. What is Polymorphism?

Polymorphism is composed of two words “poly” which means “many”, and “morph” which means “shapes”. Therefore Polymorphism refers to something that has many shapes.

There are two types of polymorphism.

  1. Compile Time Polymorphism is also known as Static Polymorphism/Static or Early Binding. It refers to a type of polymorphism that happens at compile time. Compile time polymorphism can be achieved through overloading.
public class MyClass{public static void main(String []args){

CompileTimePolymorphism demo = new CompileTimePolymorphism();
//In the below statement, the Compiler looks at the arguments and call method 1
System.out.println(demo.add(2,3));
// Similarly, in the below statement, the compiler calls method 2
System.out.println(demo.add(2,3,5));
}

}
class CompileTimePolymorphism{
// 1st method with name add
public int add(int x, int y){
return x+y;
}
// 2nd method with name add
public int add(int x, int y,int z){
return x+y+z;
}
}

Overloading allows the creation of several methods with the same name that differ by the type parameters or a number of parameters.

2. Run Time Polymorphism is also known as Dynamic Polymorphism/Late or Dynamic Binding. It refers to a type of polymorphism that happens at run time. Run time polymorphism can be achieved through overriding.

public class MyClass{public class MyClass{public static void main(String []args){

Vehicle car = new Car();
// In the above statement, as you can see, the object vehicle is of type Vehicle
// But the output of the below statement will be “Car move too”,
// because the actual implementation of object ‘vehicle’ is decided during runtime vehicle.move();
car.move();
vehicle = new Vehicle();
// Now, the output of the below statement will be “vehicle move”,
vehicle.move();

}
}
class Vehicle{
public void move(){
System.out.println("Vehicle move");
}
}
class Car extends Vehicle{

@Override
public void move(){
System.out.println("Car move too");
}
}

Q. What is Inheritence?

The idea of inheritance is simple, a class is based on another class and uses data and implementation of the other class. The purpose of inheritance is Code Reuse.

Q. What are the limitations of inheritance?

Yes, with more powers comes more complications. Inheritance is a very powerful feature in OOPs, but it has some limitations too. Inheritance needs more time to process, as it needs to navigate through multiple classes for its implementation. Also, the classes involved in Inheritance — the base class and the child class, are very tightly coupled together. So if one needs to make some changes, they might need to do nested changes in both classes. Inheritance might be complex for implementation, as well. So if not correctly implemented, this might lead to unexpected errors or incorrect outputs.

Q. What are the various types of inheritance?

Following are the types of inheritance

  1. Single inheritance
  2. Multiple inheritances
  3. Multi-level inheritance
  4. Hierarchical inheritance
  5. Hybrid inheritance

Q. How much memory does a class occupy?

Classes do not consume any memory. They are just a blueprint based on which objects are created. Now when objects are created, they actually initialize the class members and methods and therefore consume memory.

Q. Is it always necessary to create objects from class?

No. An object is necessary to be created if the base class has non-static methods. But if the class has static methods, then objects don’t need to be created. You can call the class method directly in this case, using the class name.

Q. What is an interface?

An interface refers to a special type of class, which contains methods, but not their definition. Only the declaration of methods is allowed inside an interface. To use an interface, you cannot create objects. Instead, you need to implement that interface and define the methods for their implementation.

Q. What is an abstract class?

An abstract class is a special class containing abstract methods. The significance of abstract class is that the abstract methods inside it are not implemented and only declared. So as a result, when a subclass inherits the abstract class and needs to use its abstract methods, they need to define and implement them.

Q. How is an abstract class different from an interface?

Interface and abstract class both are special types of classes that contain only the methods declaration and not their implementation. But the interface is entirely different from an abstract class. The main difference between the two is that the subclass must define all its methods and provide its implementation when an interface is implemented. Whereas when an abstract class is inherited, the subclass does not need to define its abstract method, until and unless the subclass is using it.

Also, an abstract class can contain abstract methods as well as non-abstract methods.

Q. What are inline functions?

An inline function is a technique used by the compilers and instructs to insert the complete body of the function wherever that function is used in the program source code.

Q. What is virtual function?

A virtual function a member function that is declared within a base class and is re-defined(Overriden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.

Q. What is pure virtual function?

A pure virtual function (or abstract function) is a virtual function for which we don’t have an implementation, we only declare it. A pure virtual function is declared by assigning 0 in the declaration.

Q. Difference between pure virtual function and virtual function?

This is the concepts of Run-time polymorphism and these functions can’t be global or static.

Q. What is a final variable?

A final variable means a variable whose value doesn’t change.

Q. What is meant by an exception?

An exception is an event raised during a program execution caused by undesirable input or a condition that prevents further processing. An exception causes an interruption in the program’s normal execution and must be handled via exception handling logic to avoid the program’s termination.

Q. Define exception handling

Exception handling refers to the mechanism used for handling the exceptions raised during program execution. It allows for the graceful handling of undesirable results.

Q. Is an error basically the same as an exception?

An error means a problem that the program should not catch while the exception implies a condition that should be caught by the program.

Q. What is the difference between error and exception?

Q. What is a try-catch block?

A try-catch block is used for exception handling. The set of statements that may cause a potential error are enclosed in a try block. When an exception is raised, it is caught by the catch block. The logic to handle an exception is placed inside the catch block.

Q. What is finally block?

A finally block is used to execute essential statements such as free the memory, close files, or database connections, even if an exception occurs. The finally block always runs.

Q. What is the method ‘finalize’ used for?

The finalize method is called to free the unused resources before the garbage collector gets initiated.

Q. What is a Garbage Collection, and how does it work?

Garbage collection is the ability of the programming language to perform automatic memory management. It automatically frees up the memory by removing the objects that are no longer required.

Q. What is a constructor?

A constructor method is used for initializing the objects. They are special types of methods and have the same name as the class.

Following are the types of the constructor:

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor

Q. What is a destructor?

A destructor is a method used for freeing up the resources allocated to an object. This method is automatically invoked when an object is being destroyed.

Q. What is a copy constructor?

A copy constructor helps in cloning objects by replicating the values from one object into another object which belongs to the same class.

Q. What is meant by Structured Programming?

Structured programming is a type of programming that involves breaking the program into smaller modules of code. The overall program logic is divided into functions to provide a logical structure. It is based on a top-down approach. Structural programming is suitable for easy to moderately complex problems.

Q. What is the difference between class and structure?

A class means a user-defined template from which objects are created at runtime. A class is made up of methods that provide the logic for various behaviors supported by the objects.

A structure means a user-defined combination of attributes of various data types.

Q. What are access specifiers?

Q. What are the three arguments of a ternary operator?

The ternary operator is an operator that takes three arguments. The first argument is a comparison argument, the second is the result upon a true comparison, and the third is the result upon a false comparison.

Q. What is the super keyword?

The super keyword is used to invoke the overridden method, which overrides one of its superclass methods. This keyword allows to access overridden methods and also to access hidden members of the superclass.

It also forwards a call from a constructor, to a constructor in the superclass.

Q. What is the default access modifier in a class?

Default

Q. Whether static method can use nonstatic members?

No

Q. Can you specify the accessibility modifier for methods inside the interface?

In Java, all methods in an interface are public even if we do not specify public with method names. Also, data fields are public static final even if we do not mention it with field names. Therefore, data fields must be initialized.

Q. What is Cohesion and Coupling in OOP?

Cohesion refers to what the class (or module) can do. Low cohesion would mean that the class does a great variety of actions — it is broad, unfocused on what it should do. High cohesion means that the class is focused on what it should be doing, i.e. only methods relating to the intention of the class.

Example: Suppose we have a class that multiplies two numbers, but the same class creates a pop-up window displaying the result. This is an example of a low cohesive class because the window and the multiplication operation don’t have much in common.
To make it high cohesive, we would have to create a class Display and a class Multiply. The Display will call Multiply’s method to get the result and display it. This way to develop a high cohesive solution.

// Java program to illustrate
// high cohesive behavior
class Multiply {int a = 5;
int b = 5;
public int mul(int a, int b){this.a = a;
this.b = b;
return a * b;

}
}
class Display {public static void main(String[] args){Multiply m = new Multiply();
System.out.println(m.mul(5, 5));

}
}

As for coupling, it refers to how related or dependent two classes/modules are toward each other. For low-coupled classes, changing something major in one class should not affect the other. High coupling would make it difficult to change and maintain your code; since classes are closely knit together, making a change could require an entire system revamp.

Good software design has high cohesion and low coupling.

Q. What are different types of arguments?

A parameter is a variable used during the declaration of the function or subroutine, and arguments are passed to the function body, and it should match with the parameter defined. There are two types of Arguments.

  1. Call by Value: Call by Value means calling a method with a parameter as value. Through this, the argument value is passed to the parameter. In call by value, the modification done to the parameter passed does not reflect in the caller’s scope

Example

public class Tester{
public static void main(String[] args){
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}

Output

Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45

2. Call by Reference: While Call by Reference means calling a method with a parameter as a reference. Through this, the argument reference is passed to the parameter. In the call by reference, the modification done to the parameter passed are persistent and changes are reflected in the caller’s scope.

Example

public class JavaTester {
public static void main(String[] args) {
IntWrapper a = new IntWrapper(30);
IntWrapper b = new IntWrapper(45);
System.out.println("Before swapping, a = " + a.a + " and b = " + b.a);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be different here**:");
System.out.println("After swapping, a = " + a.a + " and b is " + b.a);
}
public static void swapFunction(IntWrapper a, IntWrapper b) {
System.out.println("Before swapping(Inside), a = " + a.a + " b = " + b.a);
// Swap n1 with n2
IntWrapper c = new IntWrapper(a.a);
a.a = b.a;
b.a = c.a;
System.out.println("After swapping(Inside), a = " + a.a + " b = " + b.a);
}
}
class IntWrapper {
public int a;
public IntWrapper(int a){ this.a = a;}
}

Output

Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be different here**:
After swapping, a = 45 and b is 30

Q. What are non-access specifiers/modifiers in Java?

  1. static
  2. final
  3. abstract
  4. transient
  5. volatile
  6. synchronized
  7. native

--

--