Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Basics OOPs Interview Questions
2.1.
1. What is meant by the term OOPs?
2.2.
2. What is the need for OOPs?
2.3.
3. What are some of the most important features of OOPS?
2.4.
4. What do you mean by Structured Programming?
2.5.
5. Can instances of abstract classes be created?
2.6.
6. Describe method overloading.
2.7.
7. What is Inheritance?
2.8.
8. What is Garbage Collection in the OOP System?
2.9.
9. Can Java applications be executed without following OOP?
2.10.
10. What are interfaces?
2.11.
11. What is the main difference between classes and structures?
2.12.
12. What are pure virtual functions?
2.13.
13. What is Abstraction?
2.14.
14. What are exceptions?
2.15.
15. What is a superclass? 
2.16.
16. What are constructors?
2.17.
17. What are destructors?
2.18.
18.  What do you mean by OOPs?
2.19.
19. Name some programming languages that use the concept of OOPs?
2.20.
20. What is the need for Object-oriented programming?
2.21.
21 - What are the essential features of OOPs?
2.22.
22. Discuss the advantages and disadvantages of OOPs?
2.23.
23. What are the classes and objects in OOPs?
3.
Advanced OOPs Interview Questions
3.1.
24. What are the differences between OOPs and structural programming?
3.2.
25. What are the differences between class and object?
3.3.
26. What are the differences between class and structure?
3.4.
27. Do class and object acquire any memory?
3.5.
28. How do we define a class and declare objects in it?
3.6.
29. What are access specifiers in OOPs?
3.7.
30. What are the different types of access modifiers?
3.8.
31. What are a subclass and a superclass?
3.9.
32. What is a constructor?
3.10.
33. What are the different types of constructors?
3.11.
34. What are destructors?
3.12.
35. What is a friend function?
3.13.
36. What is an abstract class?
3.14.
37. In C++, what is the difference between a struct and a class?
3.15.
38. Explain different types of inheritance.
3.16.
39. What are the drawbacks of using inheritance?
3.17.
40. What are the drawbacks of using polymorphism?
3.18.
41. Explain static and dynamic binding.
3.19.
42. Explain a base class, a subclass, and a superclass.
3.20.
43. Give a real-life example of polymorphism.
3.21.
44. Explain abstract classes and abstract methods.
3.22.
45. What is casting in OOPs? Explain different types of casting.
3.23.
46. What are the operators which we cannot overload?
3.24.
47. Can we make a constructor private?
3.25.
48. What is a Garbage collection? What are the different types of Garbage collectors?
3.26.
49. What is the difference between an error and an exception?
3.27.
50. Can we use both super() and this() method in inside a constructor?
4.
OOPs Coding Problems
4.1.
1. Create a class Person with attributes name and age. Create an object of the class and print the person's details.
4.2.
Python
4.3.
Python
4.4.
2. Create a class Student that inherits from Person with an additional attribute roll_number. Create a student object and print their details.
4.5.
Python
4.6.
Python
4.7.
3. Create a class BankAcc with private attributes balance. Implement methods of deposit and withdraw to update the balance.
4.8.
Python
4.9.
Python
4.10.
4. Create an abstract class Bird with an abstract method speak(). Implement subclasses Sparrow and Parrot with their specific speak() methods.
4.11.
Python
4.12.
Python
4.13.
5. Create a class Shape with a method area() that returns the area of the shape. Implement subclasses Triangle and Square with their specific area() methods.
4.14.
Python
4.15.
Python
4.16.
6. Create a class MathUtils with a static method ‘product’ to multiply two numbers.
4.17.
Python
4.18.
Python
4.19.
7. Create a class Temp with an attribute celsius. Implement getter and setter methods for celsius to convert to Fahrenheit.
4.20.
Python
4.21.
Python
4.22.
8. Create a class Bird with a method speak() that returns "Bird sound". Create a subclass Sparrow that overrides speak() to return "Chirp!".
4.23.
Python
4.24.
Python
4.25.
9. Create a class Vector to represent a 2D vector. Implement the __add__ method to allow adding two vectors.
4.26.
Python
4.27.
Python
4.28.
10. Create a base class Animal with an abstract method make_sound(). Implement subclasses Dog, Cat, and Cow with their specific make_sound() methods.
4.29.
Python
4.30.
Python
5.
OOPs MCQ
6.
Frequently Asked Questions
6.1.
What are OOPs in interview questions?
6.2.
What are the 4 basics of OOP?
6.3.
What are the 5 concepts of OOPs?
6.4.
What is polymorphism in OOPs?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Top 50 OOPs Interview Questions and Answers in 2023

gp-icon
Interview guide for product based companies
Free guided path
12 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Object-Oriented Programming or OOP models can easily use or modify how programs and data interact with other objects. OOP Systems or OOPS make it easy to define the method during runtime and allow a diverse set of implementations.

OOP interview questions

OOP is one of the most popular models of programming, and multiple popular languages such as C++, Java, and Python follow the OOP methodology. Understanding the basic concepts of this programming paradigm can help answer most OOPS Interview Questions, and reviewing commonly asked questions can help with Java OOPs interview questions or other OOPS technical interview questions.

Let’s check examples of how classes, objects, characteristics, or behavior are used in the OOP approach.

  • Class: Dogs or Animals can be classes.
     
  • Object: In this case, specific dogs such as Labradors or an animal such as a bull are objects, respectively.
     
  • Characteristics: Characteristics would be the color of the labrador or the bull, their size, their weight, or other features.
     
  • Behavior: This defines or declares how the labrador or bull lives, eats, and fundamentally functions. Behaviors are the functions given to the objects or their characteristics.
     

Also See, Manual Testing Interview Questions and Power Electronics Interview Questions

Basics OOPs Interview Questions

1. What is meant by the term OOPs?

OOP stands for Object Oriented Programming. It is basically a programming technique that binds that data and function together into classes and objects to increase software readability, maintenance and security.

2. What is the need for OOPs?

OOPs helps in defining the structure of the code. It also avoids code repetition and eases the efforts to maintain or debug the code. With the help of OOPs we can write reusable and secure code which reduces the engineering efforts and increase the quality of the software.

3. What are some of the most important features of OOPS?

The main features that OOPS offers are polymorphism, abstraction of data, inheritance, and encapsulation. You can also learn more about Features of Object Oriented Programming here.

4. What do you mean by Structured Programming?

Structured Programming can be defined as programming that boasts of a structured control flow that is complete. Structures can also be referred to as blocks that contain sets of rules and are governed by definitive control flows. For example, if, then, while, else, for any other sub-routines.

The OOPS model features structure programming as it is one of the most fundamental controlled approaches for defining structures.

5. Can instances of abstract classes be created?

We cannot create instances of abstract classes as they do not have complete or absolute implementations. However, we can create instances of subclasses that inherit the abstract classes.

6. Describe method overloading.

This is one of the top 50 OOPS interview questions. Method loading can be defined as a valuable function of OOPS that allows multiple functions or methods to possess the same name. Even with identical method names, the arguments are different, and the call-to-the-methods are resolved in accordance with these arguments.

Click on the following link to read further: Javascript Interview Questions and Answers

7. What is Inheritance?

In OOP, inheritance can be defined as the process through which objects or classes are created by defining other objects or classes. The ‘child’ is the object that inherits, while the ‘parent’ is where the attributes or behavior is inherited from.

Inheritance allows implementations to become much simpler while also facilitating code reusability. Here are the five different types of inheritances:

  • Single inheritance
     
  • Hierarchical inheritance
     
  • Multiple inheritances
     
  • Hybrid inheritance
     
  • Multi-level inheritance

8. What is Garbage Collection in the OOP System?

OOPS is based on entities such as objects that consume memory with multiple objects in each class. So, it is crucial to control the memory and objects effectively, failing which might lead to errors, failures, or even system crashes.

Fundamentally, garbage collection can be defined as the system of handling memory-related tasks in the program. Garbage collection helps in removing unwanted objects that are not required, thus freeing memory.

9. Can Java applications be executed without following OOP?

Java applications cannot be run without OOPS implementations. Java itself is based on the OOP System, and it is an object-oriented programming language. Practicing OOPS coding questions in Java and checking other Java OOPs coding questions is highly advised.

However, languages such as C++ can be used with or without OOPs. It is also advised to practice OOPS viva questions in C++ and prepare for the technical questions on the OOPS concept.

10. What are interfaces?

Interfaces are used for declaring a method without specifically defining this method. Interfaces must be defined by the classes that implement the methods of the interfaces. Interfaces, however, do not contain instructions or behaviors to be executed and hence are not templates or blueprints for the program.

11. What is the main difference between classes and structures?

Classes are user-defined blueprints that cover the created objects and contain the sets of instructions or methods that must be passed through the objects. Meanwhile, structures are user-defined sets of variables that contain various data types.

12. What are pure virtual functions?

Pure virtual functions are abstract functions that only get declared in the base classes. A pure virtual function does not contain definitions in the base classes and must be redefined inside the subclasses.

13. What is Abstraction?

Abstraction can be defined as a method of hiding details that are not required from the important ones. Abstraction is one of the primary features of the OOP system. For example, an animal’s behavior might be known, but how it does it or what goes on inside its body is unknown.

14. What are exceptions?

Exceptions can be defined as special occurrences or events. These anomalies or events are raised during runtimes when programs are executed, fundamentally leading to the execution failing or stopping. Unspecified or undesirable inputs are two of the main causes that can lead to exceptions.

15. What is a superclass? 

Superclasses refer to the classes that allow other classes or any other class to inherit functions or behaviour. Animals would be the superclass of dog, bull, and lion classes. This is only true if all these classes have inherited something from the same superclass.

16. What are constructors?

Constructors are special methods that share the name with the class. Constructors help in initializing objects and when classes are instantiated using member data. Constructors then use these methods or data to assign them to objects.

17. What are destructors?

Destructors are special methods that free up memory or resources occupied by objects. Destructors are used when objects need to be removed and destroyed, fundamentally being automatically called during these scenarios. 

18.  What do you mean by OOPs?

Ans - OOPs stand for object-oriented programming. As the name suggests, this is a pattern of programming that emphasizes more on objects and classes rather than functions. It is not a programming language but a paradigm used by almost all new generations of programming languages like Java, C++, etc.

19. Name some programming languages that use the concept of OOPs?

Ans - Nowadays, almost all programming languages use object-oriented concepts.

Some of them are mentioned below.

  • C++
  • Java
  • Python
  • C#
  • Ruby

20. What is the need for Object-oriented programming?

Ans - As we evolve, our problems also become more complex and the code. To solve this problem of writing complex codes, we need object-oriented programming. It allows reusability of code which shortens the code to a greater extent. The primary importance of OOPs is to bind together the data and the functions that operate on them with the help of its essential features. 

21 - What are the essential features of OOPs?

Ans - There are four main pillars of object-oriented programming

Encapsulation

As the name suggests, It is the wrapping up of data and methods (functions) that manipulates them in a single unit. It is one of the essential features of OOPs and is achieved with the help of access modifiers.

Polymorphism

Polymorphism in OOPs refers to the objects created that can take many forms in different instances. The Word polymorphism has been made from "poly," which means many, and "morphs," which means forms. It can also be understood as function overloading, as in it, any object or method gets to act differently on different instances.

Inheritance 

The capability of a class to derive properties and characteristics from another class is called Inheritance. It is an actual world entity that gets implemented in OOPs.

There are three different modes of Inheritance.

  • Public mode
  • Protected mode
  • Private mode
  • These modes of Inheritance are used in OOPs according to the requirements.
  • Inheritance can be further divided into six types
  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance
  • Multipath Inheritance
     

Data abstraction

It is the concept of object-oriented programming which shows only the necessary attributes of a code and hides all the unnecessary things. It helps in avoiding code duplication and thus increases reusability.

22. Discuss the advantages and disadvantages of OOPs?

Following are some of the advantages of OOPs

  • Decreases the complexity of the code
  • It allows code reusability rather than rebuilding the same thing again and again.
  • It enhances the security of the code with the help of data abstraction
  • We can easily extend the code without disturbing other functionalities.
  • It helps in creating a flexible piece of code
  • Easy handling and manipulation of code
  • It follows a bottom-up approach
  • The following are the disadvantages of OOPs
  • Requires more time to get executed
  • Programmers need to be highly proficient in handling objects 
  • It can get a little tricky sometimes
  • Not suitable for all types of problems

23. What are the classes and objects in OOPs?

A class in object-oriented programming is a user-defined data type that contains a type's variables and methods(functions). A class object can only access these data variables and member functions.

An object in object-oriented programming is nothing but an instance of a class used to access a class's data members and member functions.

Also see,  Characteristics of OOPS

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Advanced OOPs Interview Questions

24. What are the differences between OOPs and structural programming?

Object-oriented programming Structural programming
It is used to solve lengthily and complex problems It is used to solve moderate or easy level problems
Follows a bottom-top approach Follows a top-bottom approach
Offers reusability of code Reusability of code is not allowed
It is more secure It is less secure
It uses the concept of inheritance It does not use the concept of inheritance
The code is more flexible Generates less flexible code
Uses data abstraction to hide unnecessary information Does not hide anything from the user

25. What are the differences between class and object?

                          Class                       Object
Class is a template on which objects are declared. An object is an instance of the class.
When a class is created, no memory is allocated Whenever an object is created. Memory is allocated.
It is a logical entity. It is an actual entity.
It has to be declared only once. It can be declared multiple times as per the requirements.
A class can exist without an object. An object cannot exist without a class.

26. What are the differences between class and structure?

                            Class                       Structure
We declare a class using the ‘class’ keyword. We declare a structure using the ‘struct’ keyword.
Members of the class are private by default. Members of the structure are public by default.
Inheritance is supported. Inheritance is not supported.
It is of reference type. It is of a value type.
It can deal with both variables and functions. It can only deal with variables.

27. Do class and object acquire any memory?

When we build a class, no memory is allocated to it as it is just a blueprint. But when an object of the class is created, memory is allocated accordingly. 

28. How do we define a class and declare objects in it?

Let us look at the syntax for it.

Class class_name

{

Access specifier; (It can be of any type)

Data members;

Member functions();

};

Note:- The body or the definition of a class always ends with a semicolon.

29. What are access specifiers in OOPs?

Access specifiers or the access modifiers decide how a foreign class can access the data members and member functions inside a class.

They are used to implement data abstraction in the program. 

Know What is Object in OOPs here in detail.

30. What are the different types of access modifiers?

Public members

The class members declared under the public specifier can be accessed by everyone, including other classes and functions.

It can be accessed anywhere through the dot (.) operator.

Private members

The class members who are declared private can only be accessed within the class. Any foreign class or a function can not access these private members. But a friend function can access the private members.

If we want to access variables declared private outside the class, we can access them through the member functions declared as public.

Protected members

The class members who are declared protected can only be accessed by their derived classes, also known as subclasses.

31. What are a subclass and a superclass?

 The classes derived from another class are called a subclass or a child class.

 The classes which derive a subclass from them are called a superclass. Both of these are 

  a concept based on inheritance.

32. What is a constructor?

It is a particular type of function that does not have a return type. The role of a constructor is to initialize the object of the class and allocate memory to it. The name of the class and the constructor will always be the same.

33. What are the different types of constructors?

There are three types of constructors.

Default constructor.

These are the constructors automatically generated by the compiler whenever an object is created. These do not have any kind of parameters or arguments in them.

Parameterized constructor 

As the name suggests, these constructors take arguments according to the requirement. Parameterized constructors can be understood as similar to passing parameters inside a member function.

Copy constructor

A copy constructor initializes the object using another object from the same class.

34. What are destructors?

Destructors are particular member functions called to free up space whenever an object is destroyed. It is just the counterpart of a constructor.

The symbol of a destructor is (~).

35. What is a friend function?

A friend function is a privileged function that can access all private and protected information. It is declared using the ‘friend’ keyword in c++.

It is language constrained, and is recommended not to use so many friend functions in a program. This can lead to a security lapse and violate the object-oriented paradigm.

36. What is an abstract class?

An abstract class is a particular type of class that can only contain declarations of abstract methods. Whenever a subclass inherits an abstract class, they need to define and implement them.

In this manner, we saw advanced questions on OOPs, which are more likely to be asked in an interview. If not in an interview, it will help you enhance your overall concept on the topic of OOPs. As it is said, if you want to get confident on a particular topic, you should practice more and more questions on it.

Let us now see some frequently asked questions related to OOPs, and subsequently, we will summarize the blog.

37. In C++, what is the difference between a struct and a class?

Both structure and class are user-defined data types in C++. The major difference between both of them is that members are by default public in structure, while in class, the members are by default set to private. So if we want to access the members of a class, we need to explicitly declare them public.

Another difference is the struct keyword is used to create a structure, and a class keyword for creating a class.

38. Explain different types of inheritance.

There are mainly five types of inheritance which are as follows:

  • Single Inheritance: The child classes are derived directly from the base class.
     
  • Multiple Inheritance: The child classes are derived from multiple base classes.
     
  • Multilevel Inheritance: The child classes are derived from the classes which are derived from other base classes.
     
  • Hierarchical Inheritance: Multiple child classes are derived from a single base class. 
     
  • Hybrid Inheritance: This inheritance is a combination of multiple types of inheritance.

39. What are the drawbacks of using inheritance?

Even though inheritance is a strong feature of OOPs, there are a few drawbacks of using inheritance which are as follows:

  • As there is no particular direction in inherited functions, they are slow compared to normal functions.
  • If inheritance is not used properly, it may lead to wrong solutions.
  • Often time after declaring the base class, many data members are not used, which leads to memory wastage.
  • The child class and base class are tightly coupled, therefore, changing one class results in changes in another.

40. What are the drawbacks of using polymorphism?

Some drawbacks we should consider while using polymorphism are as follows:

  • Polymorphism greatly affects the readability of the code.
  • Polymorphism is highly complex in order to implement and use.
  • There may be various performance issues while using polymorphism.

41. Explain static and dynamic binding.

The term binding in OOPs refers to the binding of a name to the class. 

  • Static binding: In static binding, the name is associated with the class during compilation time, and thus it is also called as early binding.
  • Dynamic binding: In dynamic binding, the name is associated with the class during runtime, and therefore it is called late binding.

42. Explain a base class, a subclass, and a superclass.

A class is categorized depending on inheritance into three types which are as follows:

  • A base class is the root class through which all child classes are derived.
  • A subclass is a class that is inherited from one or more than one base class.
  • A superclass is the parent class through which all other classes are inherited.

43. Give a real-life example of polymorphism.

One real-life example where polymorphism is used is virtual functions in C. In C, the virtual functions are used to effectively print a list of objects that are combined with different functions to return different results. This, alongside the outputs of the behaviour of the objects on the list not being specified before runtime, is a great real-life example of polymorphism.

44. Explain abstract classes and abstract methods.

In OOPs, abstraction is used to hide unnecessary implementation details and show only the necessary details.

Abstract class

  • Abstract classes do not allow any objects to be inherited from them.
  • An abstract class can contain both abstract and non-abstract methods. 
  • The abstract class cannot be instantiated.
     

Abstract method

  • An abstract method has only a signature but does not have a body.
  • An abstract method has no definition in the class and must be implemented in the derived class.
  • All the abstract methods of an abstract class must be implemented by sub-classes.

45. What is casting in OOPs? Explain different types of casting.

In C++, a pointer is used to form a relation between the parent and the child class; this is known as casting. There are two types of casting which are as follows:

Upcasting

  • Upcasting means to typecast a child object to a parent object.
  • Upcasting allows both implicit and explicit upcasting.
  • Upcasting allows access to methods and variables of the parent class.
     

Downcasting

  • Downcasting is to typecast a parent object to a child object.
  • In Java, only explicit downcasting is allowed.
  • Downcasting allows access to methods and variables of both parent and child classes.

46. What are the operators which we cannot overload?

Below are the operators which cannot be overloaded.

  • Dot operator ( . )
  • Scope resolution operator ( :: )
  • Ternary operator ( ? : )
  • Size operator ( sizeof )
  • Type operator ( typeid )
  • Pointer to a member operator ( .* )

47. Can we make a constructor private?

Yes, we can declare a constructor private. Once we declare the constructor as private, then object creation of that class will not be possible. These constructors are used in singleton design patterns. 

Below are some rules for a private constructor:

  • A private constructor does not allow us to create objects outside the class.
  • A private constructor should be used when all the methods are static.
  • A compile-time error will occur whenever we extend a class with a private constructor.

48. What is a Garbage collection? What are the different types of Garbage collectors?

Garbage collection is an a automatic process of reclaiming all unused runtime memory. The Garbage collector frees up all the spaces which are occupied by objects that are no longer in existence.

Below are the different types of Garbage collectors:

  • Serial Garbage collector
  • Parallel Garbage collector
  • CMS Garbage collector
  • G1 Garbage collector

49. What is the difference between an error and an exception?

Given below are the differences between error and exception in OOPs.

Sr No.   Error Exception
1 It is classified as an unchecked type. It is classified as both checked and unchecked type.
2 Error recovery cannot be done. Exception recovery is done using a try-catch block.
3 Programs running environment causes an error. A program itself causes exceptions.
4 It occurs at runtime and is unknown to the compiler.                                                                             Exceptions also occur at run time, but unchecked exceptions are not known to the compiler while checked are known. 

50. Can we use both super() and this() method in inside a constructor?

Both super and this method are used to make constructor calls in OOPs. The super() method is used to call the constructor of the base class, while this() method is used to call the constructor of the current class.

Using both the super() and this() method inside a constructor is not allowed and will result in a compile-time error. Both of these methods must be the first executable statements whenever we use them. Thus, whenever the first method is written as the first executable statement, then automatically, the second method will be treated as the second executable statement. Therefore, the use of both super() and these ( ) methods is not allowed together in a constructor.

OOPs Coding Problems

1. Create a class Person with attributes name and age. Create an object of the class and print the person's details.

  • Python

Python

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

person1 = Person("Jacob", 25)
print(f"Name: {person1.name}, Age: {person1.age}")

 

Output

  • Python

Python

Name: Jacob, Age: 25

2. Create a class Student that inherits from Person with an additional attribute roll_number. Create a student object and print their details.

  • Python

Python

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

person1 = Person("Rita", 25)
print(f"Name: {person1.name}, Age: {person1.age}")

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

student1 = Student("Ninja", 30, "101")
print(f"Name: {student1.name}, Age: {student1.age}, Roll No: : {student1.roll}")

 

Output 

  • Python

Python

Name: Rita, Age: 25
Name: Ninja, Age: 30, Roll No: : 101

3. Create a class BankAcc with private attributes balance. Implement methods of deposit and withdraw to update the balance.

  • Python

Python

class BankAcc:
    def __init__(self):
        self.__balance = 0

    def depositAmt(self, amt):
        self.__balance += amt

    def withdrawAmt(self, amt):
        if amt <= self.__balance:
            self.__balance -= amt
        else:
            print("Less balance!")

account1 = BankAcc()
account1.depositAmt(1000)
account1.withdrawAmt(500)
print(f"Balance: {account1._BankAcc__balance}")  # Accessing private attribute (Not recommended)

 

Output

  • Python

Python

Balance: 500

4. Create an abstract class Bird with an abstract method speak(). Implement subclasses Sparrow and Parrot with their specific speak() methods.

  • Python

Python

from abc import ABC, abstractmethod

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

class Sparrow(Bird):
    def speak(self):
        return "Chirp!"

class Parrot(Bird):
    def speak(self):
        return "Screech!"

sparrow1 = Sparrow()
parrot1 = Parrot()
print(sparrow1.speak())
print(parrot1.speak())

 

Output

  • Python

Python

Chirp!
Screech!

5. Create a class Shape with a method area() that returns the area of the shape. Implement subclasses Triangle and Square with their specific area() methods.

  • Python

Python

class Shape:
    def area(self):
        pass

class Triangle(Shape):
    def __init__(self, base, height):
        self.base = base
        self.height = height

    def area(self):
        return 0.5 * self.base * self.height

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

# Test the classes
triangle1 = Triangle(5, 8)
square1 = Square(4)

print(f"Triangle Area: {triangle1.area()}")
print(f"Square Area: {square1.area()}")

 

Output

  • Python

Python

Triangle Area: 20.0
Square Area: 16

6. Create a class MathUtils with a static method ‘product’ to multiply two numbers.

  • Python

Python

class MathUtils:
    @staticmethod
    def product(x, y):
        return x * y

ans = MathUtils.product(5, 10)
print(ans)

 

Output

  • Python

Python

50

7. Create a class Temp with an attribute celsius. Implement getter and setter methods for celsius to convert to Fahrenheit.

  • Python

Python

class Temp:
    def __init__(self):
        self._celsius = 0

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        self._celsius = value

    @property
    def fahrenheit(self):
        return (self._celsius * 9/5) + 32

temp1 = Temp()
temp1.celsius = 36
print(f"Temperature in Celsius: {temp1.celsius}, Temperature in Fahrenheit: {temp1.fahrenheit}")

 

Output

  • Python

Python

Temperature in Celsius: 36, Temperature in Fahrenheit: 96.8

8. Create a class Bird with a method speak() that returns "Bird sound". Create a subclass Sparrow that overrides speak() to return "Chirp!".

  • Python

Python

class Bird:
    def speak(self):
        return "Bird sound"

class Sparrow(Bird):
    def speak(self):
        return "Chirp!"

bird1 = Bird()
sparrow1 = Sparrow()
print(bird1.speak())
print(sparrow1.speak())

 

Output

  • Python

Python

Bird sound
Chirp!

9. Create a class Vector to represent a 2D vector. Implement the __add__ method to allow adding two vectors.

  • Python

Python

class Vector:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __add__(self, other):
        return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(5, 3)
v2 = Vector(1, 2)
ans = v1 + v2
print(f"Resultant Vector: ({ans.a}, {ans.b})")

 

Output

  • Python

Python

Resultant Vector: (6, 5)

10. Create a base class Animal with an abstract method make_sound(). Implement subclasses Dog, Cat, and Cow with their specific make_sound() methods.

  • Python

Python

from abc import ABC, abstractmethod

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

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

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

class Cow(Animal):
    def make_sound(self):
        return "Moo!"

# Test the classes
animals = [Dog(), Cat(), Cow()]
for animal in animals:
    print(animal.make_sound())

 

Output

  • Python

Python

Woof!
Meow!
Moo!

OOPs MCQ

  1. Which among the given is the first purely object-oriented programming language developed?
    a) C++
    b) Kotlin
    c) SmallTalk
    d) PHP

    Correct Answer: Option C
    Explanation: SmallTalk was the first programming language developed by Alan Kay, which was a purely object-oriented programming language.
     
  2. How many access specifiers are provided in C++?
    a) 1
    b) 2
    c) 3
    d) 4

    Correct Answer: Option C
    Explanation: There are three types of access specifiers in C++ which are private, public, and protected.
     
  3. How many data members can a class contain?
    a) 313
    b) 1132
    c) 2001
    d) As many as possible

    Correct Answer: Option D
    Explanation: A class can have as many data members as possible unless the memory size is not exceeded.
     
  4. In how many ways can we pass an object to a function?
    a) 3
    b) 1
    c) 4
    d) 2

    Correct Answer: Option A
    Explanation: We can pass objects to a function in three ways, pass by value, pass by reference, and pass by address.
     
  5. Which of the given places is the memory allocated for an object?
    a) ROM
    b) RAM
    c) Cache
    d) HDD

    Correct Answer: Option B
    Explanation: Initially, all the memory of an object is allocated in the RAM.
     
  6. Class is an ______ abstraction.
    a) Real
    b) Object
    c) Hypothetical
    d) Logical

    Correct Answer: Option D
    Explanation:  A class provides the logical structure of all of its objects. Thus a is also called logical abstraction.
     
  7. Which of the given is not a type of inheritance?
    a) Multiple
    b) Multilevel
    c) Hierarchical
    d) Distributed

    Correct Answer: Option D
    Explanation: Multiple, multilevel, and hierarchical are all types of inheritance, while distributed is not a type of inheritance.
     
  8. Which of the given below can show polymorphism?
    a) Overloading +=
    b) Overloading -=
    c) Overloading <<
    d) Overloading &&

    Correct Answer: Option C
    Explanation: Among the given options, only the Overloading << can show polymorphism.
     
  9. A virtual function should be ______. 
    a) public
    b) private
    c) protected
    d) default

    Correct Answer: Option A
    Explanation: A virtual function should be public.
     
  10. Dynamic allocation can be performed using ______.
    a) malloc()
    b) calloc()
    c) Both a and b
    d) None

    Correct Answer: Option C
    Explanation: Dynamic allocation can be performed using both malloc() and calloc() methods.
     
  11. What is cout in C++?
    a) Class
    b) Object
    c) Function
    d) Operator

    Correct Answer: Option B
    Explanation: In C++, cout is an object of ostream class.
     
  12. Which one of the following is not an OOPs concept?
    a) Polymorphism
    b) Inheritance
    c) Compilation
    d) Encapsulation

    Correct Answer: Option C
    Explanation: Compilation is not an OOPs concept.
     
  13. Who developed object-oriented programming?
    a) Dennis Ritchie
    b) Andrea Ferro
    c) Charles Babbage
    d) Alan Kay

    Correct Answer: Option D
    Explanation: Alan Kay was the first person who developed object-oriented programming.
     
  14. An abstract class can be final in Java.
    a) True
    b) False

    Correct Answer: Option B
    Explanation: If we make an abstract class final in Java, it will not allow us to extend the abstract class. Thus, there will be no other class to implement virtual functions.
     
  15. We can contain ______ abstract classes in a single program.
    a) 3
    b) 8
    c) 10
    d) As many as required

    Correct Answer: Option D
    Explanation: There is no restriction regarding the number of abstract classes a single program may contain.

Frequently Asked Questions

What are OOPs in interview questions?

OOP is a programming paradigm that is simply not based on methods, procedures, or functions but is more focused on objects. OOPS integrates inheritance and polymorphism features into programming and allows code and data to be bound together.

What are the 4 basics of OOP?

The four essentials of the OOP system are encapsulation, abstraction, polymorphism, and inheritance.

What are the 5 concepts of OOPs?

The five fundamental Object-Oriented concepts can be pinpointed down to classes/objects, encapsulation, polymorphism, inheritance, and interface/methods. These five are undoubtedly the main functions of OOLs or Object-Oriented languages. The ways these principles are implemented depends on the language.

What is polymorphism in OOPs?

In OOP, polymorphism can be defined as the ability to implement multiple approaches. There are two main types of polymorphism. Static Polymorphism can be defined as polymorphism that occurs during compiling time, while Runtime polymorphism occurs during execution.

Conclusion

OOPs, interview questions, and answers help candidates prepare for OOPS basic interview questions and instances thrown at them. One must have a good understanding of OOPS concepts for interviews and practice programming in languages such as Java and C++.

OOPs, interview questions generally revolve around the important features of OOP and cover OOPS programming questions; thus, one must have a good foundation of OOP for interviews. 

Recommended Readings:

 

Check out Uber Interview Experience to learn about their hiring process.

Previous article
Top 30 ServiceNow Interview Questions and Answers (2024)
Next article
Google Analytics Interview Questions
Guided path
Free
gridgp-icon
Interview guide for product based companies
12 chapters
123+ Problems
gp-badge
Earn badges and level up
Live masterclass