Object-Oriented Programming (OOP) Interview Questions

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than functions and logic. It is based on the concept of "objects," which can contain data in the form of fields (also known as attributes or properties) and code in the form of procedures (also known as methods). OOP aims to increase code reusability, scalability, and maintainability.

Key Features of OOP

  1. Encapsulation : The concept of bundling data and methods that operate on the data within a single unit (class). This helps protect the integrity of the data by restricting direct access to it.
  2. Abstraction : Hides complex implementation details and only exposes the necessary functionalities. It helps simplify code and reduce complexity.
  3. Inheritance : Allows a class to inherit properties and behaviors from another class, promoting code reuse and hierarchical relationships.
  4. Polymorphism : Enables a single function, method, or operator to take on multiple forms. It allows different classes to be treated as instances of the same class through a common interface.

Why is OOP Important?

  • Code Reusability: Inheritance allows the reuse of existing code, reducing redundancy.
  • Maintainability: Encapsulation ensures better organization and easier maintenance of the codebase.
  • Scalability: OOP facilitates modular design, making it easier to add new features.
  • Data Security: Access specifiers (public, private, protected) help in securing data.

Real-World Examples of OOP

  • Banking System: Different types of accounts (savings, current) can inherit common features from a base account class.
  • E-commerce Applications: Products, users, and orders can be represented as objects with their attributes and behaviors.
  • Gaming: Characters in a game can be created using OOP principles, where each character has its own attributes and actions.

Join our WhatsApp Channel for more resources!

Check Core Java interview questions

Basic OOP Concepts — Complete Interview Answers

1. What is the need for OOPs?

As software projects grew larger, procedural programming became harder to manage.
It didn’t model real-world entities well and often caused code duplication.

OOP was introduced to solve these issues by organizing programs around objects, which bundle both data and behavior.
This makes the code easier to maintain, reuse, and extend, helping developers manage complexity effectively.

2. What are some major Object-Oriented Programming languages?

Some of the most widely used OOP languages include Java, C++, Python, C#, Ruby, Kotlin, and Swift.
Each supports OOP principles like classes, inheritance, and polymorphism, though their implementation details vary slightly.

3. What are some other programming paradigms other than OOPs?

Apart from OOP, there are several other paradigms:

  • Procedural programming (like C): focuses on functions and procedures.
  • Functional programming (like Haskell, Scala): emphasizes immutability and pure functions.
  • Logic programming (like Prolog): uses rules and facts for reasoning.
  • Event-driven programming: used in GUIs or web development where code runs on specific events.

4. What is meant by Structured Programming?

Structured programming is a subset of procedural programming that emphasizes clear, logical control flow.
It uses constructs like loops, conditionals, and functions instead of “goto” statements.
This approach improves readability, reduces errors, and makes debugging easier.

5. What are the main features of OOPs?

The four main features, often called the pillars of OOP, are:

  1. Encapsulation – bundling data and methods into one unit.
  2. Abstraction – hiding unnecessary implementation details.
  3. Inheritance – enabling one class to derive from another.
  4. Polymorphism – allowing methods to behave differently based on context.

6. What are some advantages of using OOPs?

  • Reusability: Classes and objects can be reused across projects.
  • Scalability: Large systems can be built by combining smaller objects.
  • Maintainability: Changes in one part of the system have minimal impact on others.
  • Security: Through encapsulation and access control.
  • Real-world modeling: It matches how humans think about entities and relationships.

OOP became popular because it mirrors real-world systems using objects and interactions.
It makes collaboration easier in large teams, improves maintainability, and integrates well with modern technologies like GUI frameworks, web apps, and mobile apps.

8. What is meant by the term OOPs?

OOPs stands for Object-Oriented Programming System.
It’s a way of structuring code so that real-world entities are represented as objects that contain both data (attributes) and functions (methods) that operate on that data.

9. What are the four main principles of OOP?

The four pillars are:

  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism

Together, they make code modular, reusable, and adaptable to change.

10. Explain the difference between a class and an object.

A class is a blueprint that defines the structure and behavior of objects.
An object is an instance of that class — it has real data and can perform actions.

Example:

class Car {
  String color;
  void start() { System.out.println("Car started"); }
}

Here, Car is a class, and Car myCar = new Car(); creates an object myCar.

11. What is encapsulation? Provide an example.

Encapsulation means wrapping data and code together while restricting direct access to some parts of an object.
It protects the object’s internal state and only allows modification through defined methods.

Example (Java):

class Student {
  private int age;
  public void setAge(int a) { age = a; }
  public int getAge() { return age; }
}

Here, age is hidden from direct access, enforcing control over how it’s modified.

12. What is abstraction? How is it different from encapsulation?

Abstraction focuses on hiding complex implementation details and showing only the necessary parts. For example, when you call car.start(), you don’t need to know what’s happening inside the engine.

Difference:

Abstraction hides complexity. Encapsulation hides data and protects it from unauthorized access.

13. What is polymorphism? Explain with an example.

Polymorphism means “many forms.” It allows the same method name or operator to behave differently depending on the object.

Example:

  void draw() { System.out.println("Drawing Shape"); }
}

class Circle extends Shape {
  void draw() { System.out.println("Drawing Circle"); }
}

class Square extends Shape {
  void draw() { System.out.println("Drawing Square"); }
}

When Shape s = new Circle(); s.draw(); runs, it prints “Drawing Circle.” This is an example of runtime polymorphism.

14. What is inheritance? How does it promote code reusability?

Inheritance allows one class (child) to inherit fields and methods from another class (parent). It promotes reusability because common code can be written once in the parent class and reused by all child classes.

Example:

  void start() { System.out.println("Vehicle started"); }
}

class Car extends Vehicle {
  void drive() { System.out.println("Car driving"); }
}

Here, Car inherits the start() method from Vehicle, avoiding duplication.

15. What are access specifiers in OOP?

Access specifiers define the visibility of class members (variables and methods).
Common ones include:

  • public: accessible from anywhere.
  • private: accessible only within the same class.
  • protected: accessible within the same class and subclasses.

They help maintain encapsulation and prevent unauthorized data access.

16. What do you understand by OOP?

OOP is a programming model that structures software around objects, each representing a part of the system with its own data and behavior.
It helps design software that’s modular, reusable, and closer to real-world problem-solving.

17. Name any seven widely used OOP languages.

Java, C++, Python, C#, Ruby, PHP, and Swift are among the most popular OOP languages used across industries.

18. What is the purpose of using OOPs concepts?

The main purpose is to organize complex programs, reduce redundancy, and make code more flexible and maintainable.
It simplifies collaboration, enhances code clarity, and allows developers to add new features easily.

19. What are the four main features of OOPs?

  • Encapsulation – protects data.
  • Abstraction – hides internal complexity.
  • Inheritance – enables reusability.
  • Polymorphism – provides flexibility in behavior.

20. What are the advantages and disadvantages of OOP?

Advantages:

  • Encourages modularity and reusability.
  • Easier debugging and maintenance.
  • More secure through encapsulation.
  • Matches real-world modeling.

Disadvantages:

  • Slightly higher memory and execution overhead.
  • Initial design can be more complex.
  • Not ideal for very small or simple programs.

21. What are the limitations of OOPs?

While powerful, OOP can lead to overengineering for small tasks.
It also introduces a learning curve, and features like inheritance can sometimes make debugging harder if overused.
In performance-critical applications, abstraction can add slight overhead.

22. What are the differences between object-oriented programming and structural programming?

AspectObject-Oriented ProgrammingStructured Programming
FocusObjects and dataFunctions and logic
Data AccessRestricted (encapsulation)Global access
ReusabilityHigh (via inheritance)Limited
Example LanguagesJava, C++, PythonC, Pascal
Code OrganizationAround classesAround functions

23. What do you understand by pure object-oriented language? Why is Java not a pure object-oriented programming language?

A pure object-oriented language treats everything as an object — from data types to functions.
Examples include Smalltalk and Ruby.

Java isn’t pure OOP because it supports primitive data types (like int, char, float) that are not objects,
and it allows static methods, which exist outside of objects.

Classes and Objects

24. What is a class?

A class is a blueprint or template for creating objects.
It defines the properties (attributes) and behaviors (methods) that the objects created from it will have.
In simple terms, a class is like a design, and objects are its actual implementations.


25. What is an object?

An object is an instance of a class that represents a real-world entity.
It contains data in the form of variables and code in the form of methods.
For example, if Car is a class, then myCar is an object of that class.


26. How do you define a class in [Your Preferred Language]?

Example (Java):

class Car {
  String color;
  void drive() {
    System.out.println("Car is driving");
  }
}

Here, Car is a class with one data member (color) and one method (drive()).

27. How do you create an object from a class?

Objects are created using the new keyword in most OOP languages.

Example (Java):

Car myCar = new Car();

This creates an instance of the Car class and assigns it to the variable myCar.

28. What is the difference between a constructor and a method?

AspectConstructorMethod
PurposeInitializes objectsDefines object behavior
NameSame as class nameAny valid identifier
Return TypeNo return typeHas a return type
CallCalled automatically when object is createdCalled explicitly
OverloadingCan be overloadedCan be overloaded

29. What is a destructor? When is it called?

A destructor is a special function that is automatically called when an object is destroyed or goes out of scope. It is used to release resources like memory or file handles.

Example (C++):

public:
  ~Car() {
    cout << "Destructor called";
  }
};

In Java and Python, destructors are handled by the garbage collector automatically.

30. Can a constructor be private? Why or why not?

Yes, a constructor can be private. It is used to restrict object creation from outside the class, often in Singleton design patterns. This ensures that only one instance of the class can exist.

31. How much memory does a class occupy?

A class definition itself does not occupy memory. Memory is allocated only when objects of that class are created. The memory depends on the instance variables and data types defined within the class.

32. Is it always necessary to create objects from a class?

No, it’s not always necessary. For example, classes can contain static methods and variables, which can be accessed without creating an object. In utility or helper classes, we often don’t need to instantiate objects.

33. What do you understand by class and object? Also, give an example.

A class defines the structure, while an object is an instance of that structure. Together, they represent real-world entities in code.

Example (Java):

  String name;
  void bark() {
    System.out.println(name + " is barking");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog d1 = new Dog();
    d1.name = "Tommy";
    d1.bark(); // Output: Tommy is barking
  }
}
  1. What are the differences between class and object?

    {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '}
    AspectClassObject
    DefinitionBlueprint or template for objectsInstance of a class
    MemoryNo memory allocated until object creationOccupies memory when created
    PurposeDefines behavior and attributesUses defined behavior and stores data
    DeclarationDeclared onceCan create multiple objects
    ExampleCar classmyCar, yourCar (objects of Car)
  2. What are the key differences between class and structure?

    {' '}

    {' '}
    <tr>
      {' '}
      <th>
        <b>Aspect</b>
      </th>{' '}
      <th>
        <b>Class</b>
      </th>{' '}
      <th>
        <b>Structure</b>
      </th>{' '}
    </tr>{' '}
      

    </thead>{' '}

    {' '}
    <tr>
      {' '}
      <td>
        <b>Type</b>
      </td>{' '}
      <td>Reference type (in languages like C#, Java)</td>{' '}
      <td>Value type (in C, C++)</td>{' '}
    </tr>{' '}
    <tr>
      {' '}
      <td>
        <b>Access Specifier</b>
      </td>{' '}
      <td>Members are private by default</td>{' '}
      <td>Members are public by default</td>{' '}
    </tr>{' '}
    <tr>
      {' '}
      <td>
        <b>Inheritance</b>
      </td>{' '}
      <td>Supports inheritance</td> <td>Does not support inheritance</td>{' '}
    </tr>{' '}
    <tr>
      {' '}
      <td>
        <b>Memory Allocation</b>
      </td>{' '}
      <td>Allocated on heap</td> <td>Allocated on stack</td>{' '}
    </tr>{' '}
    <tr>
      {' '}
      <td>
        <b>Use Case</b>
      </td>{' '}
      <td>Used for complex data and behavior</td>{' '}
      <td>Used for lightweight data structures</td>{' '}
    </tr>{' '}
      

    </tbody>{' '} </table>

Encapsulation and Access Control

36. What is encapsulation?

Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP).
It refers to wrapping data (variables) and methods (functions) that operate on the data into a single unit — the class.
It helps in hiding internal details of an object and only exposing the necessary parts through public methods.

Example (Java):

public class Person {
  private String name; // private variable (hidden from outside)

  // Public method to access private data
  public void setName(String n) {
    name = n;
  }

  public String getName() {
    return name;
  }
}

Here, the name variable is hidden from direct access. It can only be modified through the public methods setName() and getName().

37. How does encapsulation improve code maintainability?

Encapsulation improves code maintainability by:

Protecting data integrity: Direct modification of sensitive data is prevented. Simplifying debugging: Since internal implementation is hidden, only specific methods need testing. Reducing code dependency: Other parts of the program rely on public interfaces, not internal details. Allowing flexibility: Changes inside the class don’t affect code that uses it.

In short, encapsulation makes code more secure, modular, and easier to manage.

38. What are getters and setters?

Getters and Setters are public methods used to access and update private variables of a class. They are a key part of implementing encapsulation.

Example (Java):

  private int age;

  // Getter method
  public int getAge() {
    return age;
  }

  // Setter method
  public void setAge(int a) {
    if (a > 0) {
      age = a;
    }
  }
}

Here, the getter provides read-only access, and the setter controls how data is written, ensuring data safety.

39. What is the difference between public, private, and protected access modifiers?

{' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '} {' '}
Access ModifierAccess LevelAccessible From
publicHighest (accessible everywhere)Within same class, package, subclass, and outside package
privateLowest (most restricted)Only within the same class
protectedModerateWithin the same class, package, and subclasses
default (no modifier)Package-level accessAccessible only within the same package

Example (Java):

  public int a;
  private int b;
  protected int c;
  int d; // default access
}

40. What is the concept of access specifiers, and when should we use these?

Access specifiers (also known as access modifiers) are keywords in object-oriented programming that control the visibility and accessibility of classes, methods, and variables.
They are essential for implementing encapsulation and ensuring that data and methods are accessed only in intended ways.

Main access specifiers:

  • public – Accessible from anywhere.
  • private – Accessible only within the same class.
  • protected – Accessible within the same class, package, and subclasses.
  • default (no modifier) – Accessible only within the same package.

When to use:

  • Use private for sensitive data or internal variables that should not be directly accessed or modified from outside the class.
  • Use protected when you want members accessible to subclasses but not to the entire program.
  • Use public for methods and variables that should be accessible to all other classes and packages.
  • Use default when you want to restrict access to within the same package.

Correct use of access specifiers improves security, maintainability, and modularity in code, while protecting against unintended modifications and misuse.

41. What is Abstraction?

Abstraction is an object-oriented programming concept that focuses on hiding implementation details and showing only the essential features of an object.
It allows programmers to focus on what an object does rather than how it does it.

Example:
When using a smartphone, you know how to call someone without knowing the internal workings of the phone system.


42. How do abstract classes differ from interfaces?

AspectAbstract ClassInterface
Can contain method implementationYesNo (Java 8+ allows default methods)
Can have constructorsYesNo
Can have instance variablesYesNo (only constants)
InheritanceSingle or multi-levelMultiple inheritance supported
Access modifiersCan be public, protected, privateAll members are public by default

43. Can we create an instance of an abstract class?

No, we cannot create an instance of an abstract class directly.
Abstract classes are incomplete by design and must be extended by subclasses that implement their abstract methods.

Example (Java):

abstract class Animal {
  abstract void sound();
}

class Dog extends Animal {
  void sound() {
    System.out.println("Bark");
  }
}

public class Test {
  public static void main(String[] args) {
    Animal a = new Dog(); // Valid
    // Animal a = new Animal(); // Invalid
  }
}

44. What happens if a subclass does not implement all abstract methods of a parent class?

If a subclass does not implement all abstract methods of its abstract parent class, then that subclass must also be declared as abstract. Otherwise, the compiler will throw an error.

45. How is abstraction implemented in different programming languages?

Java: Using abstract classes and interfaces. C#: Using abstract classes and interfaces. Python: Using abstract base classes (ABC module). C++: Using pure virtual functions.

46. How is data abstraction accomplished?

Data abstraction is achieved through abstract classes, interfaces, and access specifiers (private, protected, public). By keeping implementation details hidden, abstraction allows developers to focus on high-level functionality without worrying about the low-level code.

47. What is an abstract class?

An abstract class is a class that cannot be instantiated on its own and is designed to be a base class for other classes. It can contain abstract methods (without body) and concrete methods (with implementation).

Example (Java):

  abstract void draw();
  void display() {
    System.out.println("Displaying shape");
  }
}

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

An abstract class can have both implemented and abstract methods, instance variables, and constructors. An interface can only have method declarations (Java 8+ allows default methods) and constants. Interfaces support multiple inheritance, whereas a class can inherit only one abstract class directly.

49. What are the characteristics of an abstract class?

Cannot be instantiated directly. Can contain both abstract and concrete methods. Can have constructors. Can have instance variables. Used to provide a common base for subclasses to share code and ensure certain methods are implemented.

Inheritance

50. What is meant by Inheritance?

Inheritance is a core concept of Object-Oriented Programming that allows a class to acquire properties and behaviors (fields and methods) of another class.
It promotes code reusability and a hierarchical class structure.

Example: A Car class can inherit common properties from a Vehicle class instead of rewriting them.

51. What is the difference between single and multiple inheritance?

TypeDescription
Single InheritanceA class inherits from only one parent class.
Multiple InheritanceA class inherits from more than one parent class. Not directly supported in Java (interfaces are used instead).

52. What are the various types of inheritance?

  • Single Inheritance: One class inherits another class.
  • Multiple Inheritance: A class inherits from more than one class (supported in C++, but in Java it is achieved using interfaces).
  • Multilevel Inheritance: A class inherits from a derived class.
  • Hierarchical Inheritance: Multiple classes inherit from a single parent class.
  • Hybrid Inheritance: Combination of two or more types of inheritance.

53. What is a subclass?

A subclass is a class that inherits properties and methods from another class (called a superclass).
It can have its own fields and methods in addition to the inherited ones.

Example:
If Car inherits from Vehicle, then Car is a subclass of Vehicle.

54. Define a superclass.

A superclass (also called a base class or parent class) is the class whose properties and methods are inherited by another class.
It contains common features that can be shared by subclasses.

55. What is an interface?

An interface is a blueprint for a class that contains method declarations without implementations (Java 8+ allows default methods).
Interfaces define what a class should do, not how it should do it.

Example (Java):

interface Animal {
  void makeSound();
}

56. How does method overriding work in inheritance?

Method overriding occurs when a subclass provides its own implementation of a method that is already defined in its superclass. The method signature must be the same in both classes.

Example (Java):

  void sound() {
    System.out.println("Animal sound");
  }
}

class Dog extends Animal {
  void sound() {
    System.out.println("Dog barks");
  }
}

Here, Dog overrides the sound() method of Animal.

57. What is the role of the 'super' keyword in inheritance?

The super keyword in Java is used to:

Call the parent class constructor. Access parent class methods that have been overridden. Access parent class variables.

Example:

  void sound() {
    System.out.println("Animal sound");
  }
}

class Dog extends Animal {
  void sound() {
    super.sound(); // calls Animal's sound method
    System.out.println("Dog barks");
  }
}

58. Can constructors be inherited?

No, constructors are not inherited. However, a subclass can call its superclass’s constructor using the super keyword.

59. How does the 'final' keyword affect inheritance?

final class: Cannot be extended (inherited). final method: Cannot be overridden by subclasses. final variable: Value cannot be changed once initialized.

60. Are there any limitations of Inheritance?

Yes, some limitations include:

Tight coupling between parent and child classes. Overuse can make code complex and difficult to maintain. Changes in the parent class can unintentionally affect child classes. Multiple inheritance can cause ambiguity (diamond problem).

61. Explain Inheritance with an example.

Example (Java):

  void start() {
    System.out.println("Vehicle started");
  }
}

class Car extends Vehicle {
  void drive() {
    System.out.println("Car is driving");
  }
}

public class Test {
  public static void main(String[] args) {
    Car myCar = new Car();
    myCar.start(); // inherited from Vehicle
    myCar.drive(); // defined in Car
  }
}

62. Is it possible for a class to inherit the constructor of its base class?

No, a class cannot directly inherit the constructor of its base class. It can call the base class constructor using the super keyword.

63. What are the limitations of inheritance?

Increases complexity if overused. Tight coupling makes changes harder. Not suitable for all scenarios. Can cause issues like diamond problem in multiple inheritance.

64. What is the difference between Inheritance and Polymorphism?

AspectInheritancePolymorphism
DefinitionMechanism where one class acquires properties and methods of another. Ability of an object to take many forms.
PurposeCode reusability and hierarchical classification.Flexibility in behavior of objects.
TypeStructural relationship.Behavioral relationship.
ExampleCar inherits Vehicle.Method overriding in subclasses.

65. What is Polymorphism?

Polymorphism is an object-oriented programming concept that allows an entity (method, object, or operator) to take many forms.
It enables the same method name or operator to behave differently depending on the context.
Polymorphism improves flexibility and reusability in code.


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

AspectMethod OverloadingMethod Overriding
DefinitionSame method name with different parameters in the same class.Same method name and parameters in superclass and subclass.
ParametersMust differ in type or number.Must be the same.
Return TypeCan be different if parameter list differs.Must be the same or covariant.
InheritanceNo need for inheritance.Requires inheritance.
Polymorphism TypeCompile-time polymorphism.Runtime polymorphism.

67. What is meant by static polymorphism?

Static polymorphism (compile-time polymorphism) is achieved by method overloading or operator overloading.
It is resolved at compile time.

Example (Java):

class MathOperation {
  int add(int a, int b) {
    return a + b;
  }
  double add(double a, double b) {
    return a + b;
  }
}
  1. What is meant by dynamic polymorphism?

Dynamic polymorphism (runtime polymorphism) is achieved by method overriding. It is resolved at runtime, allowing flexibility in method implementation based on object type.

Example:

  void sound() {
    System.out.println("Animal sound");
  }
}
class Dog extends Animal {
  void sound() {
    System.out.println("Dog barks");
  }
}

69. Can we override a static method? Why or why not?

No, we cannot override a static method. Static methods belong to the class, not objects. Method overriding requires dynamic dispatch, which is not possible with static methods. However, static methods can be hidden using the same method signature in the subclass.

70. What is dynamic method dispatch?

Dynamic method dispatch is the process in which a call to an overridden method is resolved at runtime rather than compile-time. It is the foundation of runtime polymorphism in Java.

Example:

a.sound(); // Calls Dog's sound() at runtime
  1. What is operator overloading?

Operator overloading allows the same operator to have different meanings based on its operands. It increases code readability and flexibility.

Example (C++):

public:
  int real, imag;
  Complex operator + (Complex const &obj) {
    Complex res;
    res.real = real + obj.real;
    res.imag = imag + obj.imag;
    return res;
  }
};

72. How does C++ support Polymorphism?

C++ supports polymorphism in two ways:

Compile-time polymorphism: Achieved via function overloading and operator overloading. Runtime polymorphism: Achieved via function overriding and the use of virtual functions.

73. What is Compile-time Polymorphism and how is it different from Runtime Polymorphism?

AspectCompile-time PolymorphismRuntime Polymorphism
Also calledStatic bindingDynamic binding
Resolved atCompile timeRuntime
Achieved byMethod overloading, operator overloadingMethod overriding
PerformanceFasterSlightly slower due to dynamic dispatch
FlexibilityLess flexibleMore flexible
  1. Explain overloading and overriding with examples.

Overloading Example (Java):

  int add(int a, int b) { return a + b; }
  double add(double a, double b) { return a + b; }
}

Overriding Example (Java):

  void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
  void sound() { System.out.println("Dog barks"); }
}
  1. Give a real-world example of polymorphism.

A real-world example is a payment system that supports multiple payment methods:

  • Credit card
  • PayPal
  • Bank transfer

Each payment method implements the same interface Payment, but behaves differently when executing processPayment().

Example:

  void processPayment();
}
class CreditCard implements Payment {
  public void processPayment() { System.out.println("Processing credit card payment"); }
}
class PayPal implements Payment {
  public void processPayment() { System.out.println("Processing PayPal payment"); }
}

Here, the same method name behaves differently depending on the object type.

Advanced OOP Concepts

76. What are access specifiers and what is their significance?

Access specifiers are keywords that define the scope and accessibility of classes, methods, and variables in OOP.
They control visibility and help in encapsulation by restricting unauthorized access to data.

Significance:

  • Protect data integrity.
  • Maintain modularity.
  • Control how components interact.
  • Improve maintainability and security.

Common access specifiers include: public, private, protected, and default (package-private in Java).

77. What is a static method? How is it different from an instance method?

A static method belongs to the class rather than an instance of the class.
It can be called without creating an object.

Differences:

AspectStatic MethodInstance Method
Belongs toClassObject
Called usingClass nameObject reference
Access to instance variablesNoYes
OverridingCannot be overridden (can be hidden)Can be overridden
Memory allocationOnce per classEach object gets its own copy

Example:

class MathUtil {
  static int add(int a, int b) { return a + b; }
}
MathUtil.add(5, 10);

78. What is a singleton class? How do you implement it?

A singleton class ensures only one instance of the class exists throughout the application.

Implementation (Java):

  private static Singleton instance;
  private Singleton() {} // private constructor
  public static Singleton getInstance() {
    if (instance == null) {
      instance = new Singleton();
    }
    return instance;
  }
}

79. What are design patterns in OOP?

Design patterns are standard solutions to common software design problems. They provide reusable and efficient approaches to structuring code.

Common types:

  • Creational patterns (e.g., Singleton, Factory)
  • Structural patterns (e.g., Adapter, Composite)
  • Behavioral patterns (e.g., Observer, Strategy)

80. What is dependency injection?

Dependency Injection (DI) is a design principle where an object's dependencies are provided externally rather than being created within the object. It promotes loose coupling and easier testing.

Example: Passing a service object into a class constructor instead of instantiating it inside the class.

81. What is the difference between composition and aggregation?

AspectCompositionAggregation
OwnershipStrong ownership; part cannot exist without wholeWeak ownership; part can exist independently
Lifecycle dependencyDependentIndependent
ExampleHouse and RoomUniversity and Department

82. How do mixins work in OOP?

Mixins allow classes to incorporate methods and properties from other classes without using inheritance. They provide a way to share code across classes without forming a strict hierarchy.

Example in Python:

    def log(self, message):
        print(message)

class User(LoggerMixin):
    pass

u = User()
u.log("User logged in")

83. What is composition?

Composition is a design principle where a class is composed of one or more objects from other classes. It models a "has-a" relationship and promotes code reuse.

Example: A Car has an Engine.

84. What is the difference between Composition and Inheritance?

AspectCompositionInheritance
Relationship"Has-a""Is-a"
FlexibilityMore flexibleLess flexible
DependencyLooser couplingTighter coupling
ExampleCar has an EngineCar is a Vehicle

85. What is constructor chaining?

Constructor chaining is the process of calling one constructor from another constructor within the same class or from the superclass. It improves code reuse and readability.

Example (Java):

  Car() { this("Default Car"); }
  Car(String name) { System.out.println(name); }
}

86. What is Coupling in OOP, and why is it helpful?

Coupling refers to the degree of interdependence between classes. Low coupling is preferred because it makes code easier to maintain, test, and extend.

  1. Name the operators that cannot be overloaded.

In C++:

  • Scope resolution operator ::
  • Sizeof operator sizeof
  • Member access operators . and .*
  • Ternary conditional operator ?:

88. What is the difference between new and override?

AspectCompositionInheritance
Relationship"Has-a""Is-a"
FlexibilityMore flexibleLess flexible
DependencyLooser couplingTighter coupling
ExampleCar has an EngineCar is a Vehicle

89. What is Cohesion in OOP?

Cohesion refers to how closely related the responsibilities of a single class are. High cohesion means a class has a well-defined purpose, improving readability and maintainability.

90. What is the difference between a base class and a superclass?

Aspectnew (method hiding)override (method overriding)
PurposeHides a base class method in the derived classProvides a new implementation for a base class method
BindingCompile-timeRuntime
Keywordnew

keyword used in C#

override

keyword used in C#

Exception Handling in OOP

91. What is an exception?

An exception is an unexpected or abnormal condition that occurs during program execution, disrupting the normal flow of instructions.
Examples include division by zero, null pointer access, or file not found errors.

92. What is meant by exception handling?

Exception handling is the process of responding to and recovering from exceptions in a program.
It ensures that the program can handle errors gracefully without crashing abruptly.

In OOP, exception handling is typically implemented using try, catch, and finally blocks.

93. How do you handle exceptions in OOP?

Exceptions in OOP are handled using:

  • try block: Wraps code that might throw an exception.
  • catch block: Contains code to handle the exception.
  • finally block: Contains code that executes regardless of whether an exception occurs.

Example (Java):

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
} finally {
    System.out.println("Execution completed");
}

94. What is the difference between checked and unchecked exceptions?

TypeDescription
Checked ExceptionChecked at compile-time. Must be handled explicitly using try-catch or throws. Example: IOException.
Unchecked ExceptionChecked at runtime. No need to handle explicitly. Example: NullPointerException, ArithmeticException.

95. Can a constructor throw an exception?

Yes, a constructor can throw an exception. If an exception occurs in a constructor, object creation is aborted, and the exception must be handled appropriately.

Example (Java):

  Test() throws Exception {
    throw new Exception("Error in constructor");
  }
}

96. What is the 'finally' block used for?

The finally block is used to execute important code regardless of whether an exception occurred or not. It is commonly used to release resources like file handles, database connections, etc.

Example:

    // code that may throw exception
} catch (Exception e) {
    // handle exception
} finally {
    System.out.println("Always executed");
}

97. What are the differences between error and exception?

AspectErrorException
DefinitionSerious problems beyond the program’s control, e.g., system errors. Conditions that a program can catch and handle.
RecoverableUsually not recoverable.Can be recovered with proper handling.
ExamplesOutOfMemoryError, StackOverflowErrorIOException, NullPointerException
HandlingNot intended to be handled by program code.Handled using try-catch blocks.

9. OOP vs Procedural Programming and Real-World Applications

98. How does OOP compare to procedural programming?

AspectObject-Oriented Programming (OOP)Procedural Programming
ApproachData and functions are bundled together as objects.Focuses on procedures or functions operating on data.
Data HandlingEncapsulates data with methods for better control.Data and functions are separate.
ReusabilityHigh, through inheritance and polymorphism.Limited, code reuse is less structured.
ScalabilityHighly scalable due to modular design.Less scalable; changes may require significant modifications.
Real-world modelingModels real-world entities naturally.Less intuitive for complex systems.

99. What are the advantages of using OOP in software development?

  • Modularity: Code is organized into classes and objects.
  • Reusability: Through inheritance and polymorphism.
  • Maintainability: Encapsulation makes code easier to maintain and debug.
  • Scalability: Easier to extend and upgrade software.
  • Real-world modeling: Better representation of real-world problems.
  • Improved collaboration: Teams can work on different classes independently.

100. Can you give an example of an OOP-based real-world application?

Example: An online shopping system.

  • Objects: User, Cart, Product, Payment, Order.
  • Each object has its own data and behaviors, e.g., the Cart object can add or remove products, calculate totals, etc.
    This design makes the system modular, maintainable, and scalable.

101. What are some common pitfalls when using OOP?

  • Overengineering for simple problems.
  • Excessive inheritance, leading to tightly coupled code.
  • Ignoring design principles, which can cause code duplication.
  • Poor use of encapsulation, resulting in weak data protection.
  • Misusing polymorphism, making code unnecessarily complex.

102. How does OOP support code scalability and maintainability?

OOP supports scalability and maintainability by:

  • Encapsulation: Isolates changes within classes.
  • Inheritance: Allows extending functionality without modifying existing code.
  • Polymorphism: Lets different objects be treated uniformly, easing changes.
  • Modular design: Classes can be developed, tested, and updated independently.
    These features make OOP well-suited for large, evolving projects.

103. Can we run a Java application without implementing the OOPs concept?

Technically, yes. Java is an object-oriented language but still allows writing code without fully leveraging OOP concepts.
However, doing so would forfeit the main benefits of Java, such as modularity, reusability, and maintainability, and lead to less efficient, harder-to-maintain code.


104. Identify which OOPs concept should be used in the following scenario:

A group of 5 friends, one boy never gives any contribution when the group goes for the outing. Suddenly a beautiful girl joins the same group. The boy who never contributes is now spending a lot of money for the group.

This scenario reflects Polymorphism.
Polymorphism allows an object to behave differently based on context.
Here, the boy’s behavior changes due to a change in context (new member joining). This is analogous to a method behaving differently based on input or object state.

Miscellaneous OOP Concepts

105. What is the difference between shallow copy and deep copy?

AspectShallow CopyDeep Copy
CopiesCopies object’s top-level structure.Copies entire object along with nested objects.
ReferencesReferences are shared between copies.Each copy has its own independent references.
Memory UsageLess memoryMore memory
ExampleCopying object references in Java.Creating new objects recursively for all references.

106. How does garbage collection work in OOP languages?

Garbage collection is the process by which programming languages automatically free up memory by deleting objects that are no longer in use.
The garbage collector identifies objects without references and reclaims memory to prevent memory leaks.
Languages like Java, Python, and C# have built-in garbage collectors.

107. What is meant by Garbage Collection in OOPs world?

Garbage collection is the automatic process of identifying and freeing memory occupied by objects that are no longer referenced in the program.
It simplifies memory management and reduces the risk of memory leaks.

108. What is method chaining?

Method chaining is a technique in which multiple methods are called in a single statement, each method returning the object itself or another object so that the next method can be invoked.

Example (Java):

class Student {
  Student setName(String name) { /* set name */ return this; }
  Student setAge(int age) { /* set age */ return this; }
}
Student s = new Student().setName("John").setAge(20);

109. What is the difference between mutable and immutable objects?

AspectMutable ObjectsImmutable Objects
ChangeableCan be changed after creationCannot be changed after creation
ExamplesLists, dictionaries in PythonStrings in Java, integers in Python
AdvantagesFlexible, efficient for some use casesSafer for multithreaded environments
DisadvantagesRisk of unintended changesHigher memory usage for modifications

110. What is reflection in OOP?

Reflection is the ability of a program to inspect and modify its own structure and behavior at runtime. It allows inspecting classes, methods, and fields dynamically.

Example (Java):

Method method = obj.getMethod("myMethod");
method.invoke(obj.newInstance());

111. Are class and structure the same? If not, what's the difference between a class and a structure?

AspectClassStructure
Access specifiersPrivate by default (Java: public)Public by default
InheritanceSupportedNot supported
EncapsulationFully supportedLimited
Memory allocationReference typeValue type
ExampleJava, C++ classesC structs, C++ structs

112. What are the various types of constructors in C++?

  • Default constructor: Takes no arguments.
  • Parameterized constructor: Takes arguments to initialize objects.
  • Copy constructor: Creates a new object as a copy of an existing object.
  • Static constructor: Used in some languages (e.g., C#) to initialize static data.

113. What is a copy constructor?

A copy constructor is a special constructor in C++ that creates a new object as a copy of an existing object. It duplicates the values of the object being copied.

Example:

public:
  int x;
  Example(int val) { x = val; }
  Example(const Example &obj) { x = obj.x; }
};

114. What is a destructor?

A destructor is a special method in OOP that is automatically called when an object is destroyed to release resources. In C++, it is defined using the ~ symbol.

Example (C++):

public:
  ~Example() { cout << "Destructor called"; }
};

115. What are the manipulators in OOP, and how do they work?

Manipulators in C++ are functions used to format input and output streams. Examples: endl, setw(), setprecision(). They help in controlling output formatting without changing the actual data.

116. What are the rules for creating a constructor?

  • Name must match the class name.
  • No return type.
  • Can be overloaded.
  • Can have access specifiers.
  • Can have parameters or none (default constructor).

117. What are the differences between the constructor and the method in Java?

AspectConstructorMethod
NameSame as class nameAny valid name
Return typeNoneMust have return type
PurposeInitializes objectPerforms operations
CallAutomatically calledExplicitly called
OverloadingYesYes

118. What are the types of variables in OOP?

  • Instance variables: Belong to an object.
  • Class/static variables: Belong to the class, shared among objects.
  • Local variables: Defined inside methods, accessible only within scope.
  • Final variables: Constant variables that cannot change once assigned.

119. Is it possible to overload a constructor?

Yes, constructors can be overloaded by defining multiple constructors with different parameter lists. This allows creating objects in different ways.

120. Can we overload the main() method in Java? Also, give an example.

Yes, the main() method can be overloaded in Java, but the JVM calls only the standard public static void main(String[] args) method to start the program.

Example:

  public static void main(String[] args) {
    System.out.println("Main method with String[] args");
    main(5);
  }
  public static void main(int num) {
    System.out.println("Overloaded main method: " + num);
  }
}

Join Telegram group for more resources & discussions!

🧰 Useful Resources for Your Placement Prep