• Articles
  • Tutorials
  • Interview Questions

OOPs Interview Questions

CTA

Most Frequently Asked OOPs Interview Questions

  1. What is object-oriented programming?
  2. What are the four pillars of OOPs?
  3. What is inheritance?
  4. What are the different types of inheritance?
  5. What is encapsulation?
  6. What is abstraction?
  7. What are constructors?
  8. What is the difference between class and object?
  9. What is the purpose of interfaces in Java?

Welcome to our guide on mastering object-oriented programming (OOP) interview questions! In today’s tech world, proficiency in OOP is essential for securing top positions. Over 70% of developers worldwide prefer OOP languages. Whether you’re a seasoned developer or just starting out, understanding OOP concepts can boost your career. We’ll explore fundamental OOP concepts and common interview questions and provide insights to help you ace your next interview. From inheritance to polymorphism, we’ll cover all you need to become a proficient OOP developer. Whether it’s for your dream job interview or skill enhancement, let’s unlock the secrets of mastering OOP interview questions together!

Basic OOPs Interview Questions

1. What is object-oriented programming?

Object-oriented programming is a type of programming that revolves around objects. It mainly focuses on managing code into objects that contain data and behavior, enabling better formation, modularity, and reusability.

For example: Before creating a house we create the blueprint of the house or design in particular. Based on the design we build the house. The blueprint is called class and the finished house is called the object.

2. Name some widely used OOP languages.

Python, Java, C, C++, C#, Ruby, Go, and Dart are some of the languages that use object-oriented programming.

3. What are the four pillars of OOPs?

four pillars of OOPs

The four pillars of OOPs are:

4. Explain inheritance in OOPs.

Inheritance in object-oriented programming means that the child class will inherit all the properties of the parent class. The child class will be able to access all the methods and behavior of the parent class.

For example:  A child will inherit the house that his father owns.

5. What is encapsulation?

Encapsulation means combining all the methods and behaviors and putting them into a single place called a class. It is like a medicinal capsule that has various medicine powders combined to make one capsule.

6. What is polymorphism?

Poly means many, and morph means form. So, polymorphism allows one entity in code, such as a variable, function, or object to take many forms. This allows flexibility and adaptability in the programs.

For example: A man can be a father, an employee, a son, or a friend. It means that man has many forms.

Get 100% Hike!

Master Most in Demand Skills Now!

7. What is abstraction?

Abstraction means hiding unwanted information from customers and only displaying what they want to see.

For example: When you go to an ATM, you are only concerned about withdrawing money, not about how the money is getting withdrawn.

8. What is the difference between class and object?

A class is a blueprint of the object. It is just like a map created to build a house. It defines the attributes and behavior of the object that the class will have.

An object is an instance of a class. Like the architecture of the house tells you, it is going to have rooms, washrooms, a kitchen, doors, etc. The object will be the finished product of the same. We can create as many houses as we want using the class defined.

9. What are constructors?

A constructor is a special method that gets called whenever the object of the class is created. It has the same name as the class and no return type.

10. Explain the concept of method overloading.

Method overloading is a concept of polymorphism. In this, the classes will have multiple methods with the same name. They only differ in the number of parameters, the data type of the parameters, or the order of the parameters.

class A:

    def sum(a,b):
        return a + b;

    def sum(a,b,c):
        return a + b + c

Intermediate OOPs Interview Questions

11. What is the difference between method overloading and method overriding?

Method overloading is having a way of writing methods in a class that performs similar tasks but the parameters are in different forms, i.e., it has several methods with the same name and return type but different numbers and types of arguments. But method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.

12. Explain the concept of abstraction with the help of an example.

Abstraction refers to hiding internal details and showing functionality. For example, we have created a shape class using draw() and area() methods. Whether or not this class will be used for drawing circles or rectangles does not matter, users can interact with these methods without knowing anything about how they are implemented for particular shapes.

13. What is the purpose of interfaces in Java?

Interfaces define contracts for classes to implement with abstract methods that must be provided by implementing classes. They serve as multiple inheritance mechanisms, support polymorphism, and promote loose coupling.

14. Differentiate between abstract classes and interfaces in Java.

Both abstract classes and interfaces can contain abstract methods, non-abstract methods, as well as variables. A single class may only extend one abstract class, although it would implement many interfaces at once. Constructively, a constructor works on abstract classes rather than interfaces, which have no constructors at all.

15. What is the role of the super keyword?

The super keyword in Java is utilized to refer back to the superclass of an existing object. It has a main purpose, which is to use superclass constructors and methods within a subclass. This enables method overriding and access to superclass members.

16. Explain the concept of method overriding with an example.

When a subclass provides an implementation for a method that is already defined in its superclass, it is known as method overriding. Let us assume there exists a super class by the name of Animal with one method called makeSound(). A sub class Dog can provide an alternative sound when making this sound, thus overwriting the earlier implementation of “bark”.

17. What is the diamond problem in inheritance, and how can it be resolved?

The problem of diamond inheritance arises when a child derives from two classes that have some base class in common. When this happens, ambiguity occurs during the process of method resolution. To avoid this problem, Java uses only a single inheritance for classes but permits multiple inheritances through interface implementation.

18. What are abstract methods and abstract classes?

Abstract methods are those methods declared inside a class without giving a body for them. Abstract classes, on the other hand, are classes that contain at least one abstract method and cannot be instantiated. They lay out plans on how actual subclasses should implement these abstract methods.

19. Explain the concept of encapsulation with an example.

concept of encapsulation

Encapsulation can be understood as the inclusion of methods and variables that operate on them in one object. For instance, a class Car has private attributes such as speed and fuel. These characteristics are modified by accelerate() or refuel() without showing what is inside.

20. What is the difference between static and non-static methods in Java?

Static methods belong to the class itself rather than to instances of the class. They can be called using the class name and are shared among all instances of the class. Non-static methods, on the other hand, belong to individual instances of the class and can access instance variables.

Advance OOPs Interview Questions

21. What are the different types of polymorphism?

Two types of polymorphism are compile-time polymorphism and run time polymorphism.

Compile-Time Polymorphism: It is also called static polymorphism. The method to be invoked is determined at compile time in this case. Examples include operator overloading and function overloading.

Runtime Polymorphism: Another name for it is dynamic polymorphism; it happens when the method to be executed is decided at runtime depending on the actual type of an object. This is done by using virtual functions through method overriding, usually using inheritance features.

22. What are the different types of Inheritance?

There are 5 types of inheritance:

Single-level Inheritance: It means the child class inherits the functionalities of a single parent class. For example, a child inherits functionalities from his/her mother or father

Single-level Inheritance

Multiple-level Inheritance: It means there is more than one parent class from which the child class inherits the functionalities. For example, a child inherits the functionalities of both mother and father

Multi-level Inheritance: It means the child class inherits functionalities from a parent class, which in turn is a child class of another parent class. For example, a father inherits functionalities from his father and then the child inherits them from the father

Multi-level Inheritance

Hierarchical Inheritance: It means that multiple child classes inherit the functionalities of the parent class. In simple terms, there is one parent class and more than one child class. For example, father and uncle both inherit the functionalities of grandfather

Hierarchical Inheritance

Hybrid Inheritance: It is a combination of different inheritances. Consider a family tree and form a relation where the father and uncle inherit the functionalities of the grandfather. Then, you inherit the functionalities of both father and mother.

23. What are virtual functions?

In object-oriented programming, virtual functions are declared in a base class and then overridden in derived classes to promote polymorphism. They enable specific implementations of methods that are defined in the base class to be provided by the derived class.

The implementing code is called at runtime based on the actual object type once a function is declared as virtual. This makes it possible for a particular piece of code to be flexible and extensible.

For example, circles and rectangles can calculate area based on their shapes such as with a shape having an area() function that is made virtual. By enabling dynamic dispatch, this mechanism invokes runtime polymorphism thereby improving code reusability and extendibility.

24. What is the difference between structural programming and object-oriented programming?

Structural Programming

Focus: Major core is programs that are designed around approaches or processes in which statements are executed sequentially.
Data and Functions: Data detached from functions; data are played with through this way of function passing parameters.

Example: For instance, the input for calculation and display would each require separate functions in a rectangle area program.

Object-Oriented Programming (OOP)

Focus: Places emphasis on objects as containers of data and behavior and operating by well-defined interfaces.
Data and Functions: These entities are joined together; object-oriented programming can simply change the method name specifying how to access the data.

Example: A class called Rectangle has attributes such as length and width, then methods like calculateArea().

Comparison

Data Encapsulation: OOP upholds the bundling of functions with their related data through encapsulation.
Inheritance and Polymorphism: For code reuse purposes, OOP allows inheritance and polymorphism. 

Example: By extending the Rectangle class create a Square class that inherits properties and methods.

25. What is static and dynamic binding?

These are the mechanisms in programming languages that determine which implementation of a function or method will be called at runtime.

Static Binding

  • It is also called early binding and refers to the case where the compiler decides on the method to invoke during compile time, depending on the reference type.
  • In static binding, the method that should be called will be resolved at compile time.
  • For instance, when you use a reference variable of one Java class, such as a parent class, it actually refers to an object of another Java class, but the method in parent class will still be called.

Dynamic Binding

  • Also referred to as late binding or runtime polymorphism, it exists when the method to invoke is decided at run-time according to its actual object type.
  • In dynamic binding, the method that should be called will be resolved at run-time.
  • For example, if you have used a reference variable of some parent class in Java while referring to an object belonging to its child class, then these references would imply calling for the methods in these child classes only.

26. What are the different constructors in C++?

different constructors in C++

C++ constructors are member functions that are used to initialize objects of a class. These constructors have the same name as the class and do not have a return type. There are different kinds of constructors.

    1. Default Constructor: It is a constructor that has no arguments. It creates an object with default values or does default initialization. Example: MyClass() {}
    2. Parameterized Constructors: This type of constructor has some parameters that can be used to initialize objects with particular values. For example, MyClass(int x, int y) { … }
    3. Copy Constructor: A constructor that makes another object identical to an existing one. Like this: MyClass(const MyClass& other) { … }
    4. Constructor Overloading: Many constructors per class have different argument list(s). For instance: MyClass(int x) { … } and MyClass(int x, int y) { … }
    5. Delegate Constructor (C++11 and later): One constructor in a class calls another constructor within the same class. This, for example, is done by using the code snippet below; MyClass(): MyClass(0, 0) { …}

In C++, it is essential to use constructors when giving birth to an object; therefore, they can be modified differently for this reason.

27. What are decorators in OOPs?

Decorators are a design pattern in object-oriented programming (OOP) that adds behavior to individual objects without affecting others in the same class dynamically. In Python, they are often used to improve functions or methods by wrapping them with additional functionality. Typically, these wrappers are implemented using functions or classes, meaning that one can execute supplementary acts before or after the original function or method.

def uppercase_decorator(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result.upper()
    return wrapper

@uppercase_decorator
def greet(name):
    return f"Hello, {name}!"

print(greet("John"))  # Output: HELLO, JOHN

28. What are access specifiers?

In object-oriented programming languages such as C++, Java, and C#, access specifiers (also known as access modifiers) are keywords that determine the visibility and accessibility of class members (attributes and methods) from outside the class.

There are three main types of access specifiers:

Public: The members that are declared public; because any other class or function can access it from outside the class, it is accessible from anywhere in the program.

Protected: This member is only accessible within its subclass; for example, when you declare a variable as protected, it means this variable can be accessed by any code within this class hierarchy but not from another package outside this package hierarchy.

Private: These members remain invisible to other classes coming from anywhere else even if that happens to be its descendant class, i.e., private is restricted to 1 particular class.

class MyClass:
    def __init__(self):
        self.public_var = "I am public"
        self._protected_var = "I am protected"
        self.__private_var = "I am private"

obj = MyClass()
print(obj.public_var)      # Output: I am public
print(obj._protected_var)  # Output: I am protected
print(obj.__private_var)  # Error: AttributeError: 'MyClass' object has no attribute '__private_var'

Problem-Solving OOPs Interview Questions

29. Write a Python class named Student with attributes name and age. Create an object of this class and print its attributes.

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

student1 = Student("Alice", 20)
print(student1.name, student1.age)  # Output: Alice 20

30. Create a base class Animal with a method sound() and a derived class Dog that inherits from Animal and overrides the sound() method to return

class Animal:
    def sound(self):
        return "Generic animal sound"

class Dog(Animal):
    def sound(self):
        return "Woof!"

dog = Dog()
print(dog.sound())  # Output: Woof!

31. Create a class Shape with a method area() and two derived classes Rectangle and Circle that override the area() method to calculate the area of the respective shapes.

class Shape:
    def area(self):
        return 0

class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

rectangle = Rectangle(5, 4)
print(rectangle.area())  # Output: 20

circle = Circle(3)
print(circle.area())     # Output: 28.26

32. Create a class Account with a private attribute balance. Implement methods of deposit() and withdraw() to modify the balance.

class Account:
    def __init__(self, initial_balance):
        self.__balance = initial_balance

    def deposit(self, amount):
        self.__balance += amount

    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount
        else:
            print('Insufficient funds')

account = Account(1000)
account.deposit(500)
account.withdraw(200)

33. Create classes Leg and Body. Use composition to create a Human class composed of instances of Leg and Body.

class Leg:
def kick(self):
print("Kicking with leg")

class Body:
def walk(self):
print("Walking with body")

class Human:
    def __init__(self):
        self.leg = Leg()
        self.body = Body()

human = Human()
human.leg.kick()  # Output: Kicking with leg
human.body.walk() # Output: Walking with body

34. Create an abstract class Animal with an abstract method speak(). Implement derived classes Dog and Cat that override the speak() method.

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

dog = Dog()
print(dog.speak())  # Output: Woof!

cat = Cat()
print(cat.speak())  # Output: Meow!

35. Create a class Point with attributes x and y. Implement the __add__() method to add two Point objects.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

p1 = Point(1, 2)
p2 = Point(3, 4)
print((p1 + p2).x, (p1 + p2).y)  # Output: 4 6

36. Create a class Math with a static method add() that takes two numbers as arguments and returns their sum.

class Math:
    @staticmethod
    def add(a, b):
        return a + b

print(Math.add(3, 5))  # Output: 8

37. Create a class Date with a class method now() that returns the current date.

from datetime import date

class Date:
    @classmethod
    def now(cls):
        return date.today()

print(Date.now())  # Output: Current date

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.