Top 25+ OOPs Interview Questions & Answers [ JAVA TRICKS ] |ACTE
OOPs Interview Questions and Answers

Top 25+ OOPs Interview Questions & Answers [ JAVA TRICKS ]

Last updated on 04th Jul 2020, Blog, Interview Questions

About author

Ramesh (Sr Technical Engineer )

High level Domain Expert in TOP MNCs with 8+ Years of Experience. Also, Handled Around 20+ Projects and Shared his Knowledge by Writing these Blogs for us.

(5.0) | 15212 Ratings 3133

Object-oriented programming (OOP) is a programming paradigm centered on objects and instances of classes. Fundamental principles include encapsulation for data protection, inheritance for code reuse, polymorphism for flexible behavior, and abstraction for simplifying complexity. OOP promotes modular, reusable, and intuitive code organization by modeling software entities as objects with defined attributes and methods.

1. What is OOP?


Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of “objects,” which are instances of classes. OOP is based on four main principles: encapsulation, inheritance, polymorphism, and abstraction. It provides a modular and organized approach to software development, making it easier to design, implement, and maintain complex systems.

2. Define Encapsulation in Python.


In Python, encapsulation is achieved through naming conventions and the use of single or double underscores to indicate the visibility of attributes. While Python does not have true access modifiers like private or protected, a single underscore (_attribute) implies a protected attribute and a double underscore (__attribute) implies a private attribute.

3. Define a Class.


A class is a blueprint or a user-defined data type in OOP that represents a concept or entity in the real world. It defines the properties (attributes) and behaviors (methods) common to all objects of that type. Objects are instances of classes, and the class serves as a template for creating multiple objects with similar characteristics. 

4. What is Polymorphism?


  • Polymorphism allows objects of different types to be treated as objects of a common type.
  • This concept is achieved through method overloading and method overriding, enabling code flexibility, and supporting a dynamic and adaptable design.

5. What is Inheritance?


Inheritance is a mechanism in OOP that allows a class (subclass or derived class) to inherit properties and behaviors from another class (superclass or base class). This promotes code reuse, as the subclass can reuse and extend the functionalities of the superclass.

6. Define Abstraction.


  • Abstraction is the process of simplifying complex systems by modeling classes based on their essential features while hiding unnecessary details.
  • It involves creating abstract classes and methods, contributing to a clearer and more scalable code structure.

7. Explain Method Overriding.


Method Overriding is a feature in OOP that enables a subclass to provide a specific implementation for a method that is already defined in its superclass. This allows the subclass to tailor the behavior of the inherited method to suit its specific requirements, promoting flexibility and customization.

8. Define Constructor.


  • A constructor is a special method in a class that is automatically called when an object of that class is instantiated.
  • It is used to initialize the object’s state, allocate resources, and perform any necessary setup.

9. What is the ‘final’ keyword in Java used for?


In Java, the ‘final’ keyword has multiple uses. It can be applied to variables to make them constants, to methods to prevent them from being overridden in subclasses, and to classes to prevent them from being extended. The ‘final’ keyword ensures immutability, method stability, and class integrity, contributing to code robustness and security.

10. Explain Method Overloading.


  • Method Overloading is a feature in OOP that allows a class to define multiple methods with the same name but different parameter lists.
  • This enables a method to perform different tasks based on the type or number of its parameters.

11. Define Interface in OOP.


An interface in OOP is a collection of abstract methods that define a contract for classes implementing the interface. It provides a way to achieve multiple inheritance in Java, allowing a class to implement multiple interfaces. Interfaces are used to achieve abstraction and define a common set of behaviours that can be shared across different classes.

12. What is a Static Method?


  • A static method in OOP belongs to the class rather than an instance of the class. It is invoked using the class name rather than an object of the class.
  • Static methods are shared among all instances of a class and can be called without creating an object. 

13. Differentiate between Abstract Class and Interface.


  Feature Abstract Class Interface
Type of Methods

Mix of abstract and concrete methods

Only abstract methods
Variables Can have instance variables Cannot have instance variables

Supports single inheritance

Supports multiple inheritance
Constructor Can have constructors Cannot have constructors
Access Modifiers

Supports access modifiers

Methods are implicitly public

14. Explain the ‘this’ keyword in Java.


‘This’ in Java refers to the active instance of the class. It is employed to differentiate between similarly named method parameters and instance variables. When there is a name issue, “this” is very helpful since it guarantees accurate and clear identification of class members.

15. What is Dynamic Binding?


  • Dynamic binding, also known as late binding or runtime polymorphism, is a feature in OOP that allows the selection of a specific method implementation at runtime. 
  • It contrasts with static binding, where the method to be executed is determined at compile time. 

16. What is the Role of the ‘this’ Pointer in C++?


In C++, the ‘this’ pointer is a pointer that holds the memory address of the current object. It is used to differentiate between object attributes and method parameters when they share the same name. The ‘this’ pointer is implicitly passed to all non-static member functions and is particularly useful in situations where there is a need to reference the current object’s state.

17. Explain the four pillars of OOP.


Encapsulation: Bundling data and methods that operate on the data into a single unit.

Inheritance: Mechanism for a class to inherit properties and behaviors from another class.

Polymorphism: Allows objects of different types to be treated as objects of a common type.

Abstraction: Simplifying complex systems by modeling classes based on their essential features.

Four Pillars

18. Explain Method Signature.


  • The method signature consists of a method’s name and its parameter list, excluding the return type.
  • It defines the unique identifier for a method within a class or interface. The signature is crucial for method overloading, as two methods in the same class cannot have the same signature.

19. What is a Destructor?


A destructor in OOP is a special method that is automatically called when an object goes out of scope or is explicitly deleted. It is used to perform cleanup tasks, release resources, or deallocate memory allocated during the object’s lifetime. Destructors play a crucial role in resource management and ensuring the proper disposal of object-related resources.

20. Explain the Diamond Problem.


  • The Diamond Problem is a complication that can arise in programming languages supporting multiple inheritance, such as C++.
  • It occurs when a class inherits from two classes that share a common ancestor.

    Subscribe For Free Demo


    21. Define Friend Function in C++.


    In C++, a friend function is a function that is not a member of a class but is granted access to its private and protected members. Friend functions are declared using the ‘friend’ keyword in the class declaration. They provide a way to allow external functions or classes to interact with the private members of a class, promoting flexibility in design while maintaining encapsulation.

    22. Explain the Singleton Design Pattern.


    • The Singleton Design Pattern ensures that a class has only one instance and provides a global point of access to that instance.
    • It involves a private constructor, a private static instance of the class, and a public static method to access that instance.

    23. What is a Pure Virtual Function?


    In C++, a pure virtual function is a virtual function declared in a base class that has no implementation and is marked with ‘= 0’. A class containing a pure virtual function is considered an abstract class, and any derived class must provide an implementation for the pure virtual function to become concrete.

    24. Explain the SOLID Principles.


    Single Responsibility Principle (SRP): A class should have only one reason to change.

    Open/Closed Principle (OCP): Software entities (classes, modules, functions) should be open for extension but closed for modification.

    Liskov Substitution Principle (LSP): Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.

    Interface Segregation Principle (ISP): A class should not be forced to implement interfaces it does not use.

    Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules; both should depend on abstractions.

    25. Define Covariant Return Type.


    The covariant return type is a feature in C++ that allows a derived class method to return a type derived from the return type of the base class method. This enables a more flexible and intuitive design when dealing with polymorphism. Covariant return types make it easier for derived classes to return objects related to the base class’s return type, promoting a clearer and more natural inheritance hierarchy.

    26. What is a Memory Leak?


    • A memory leak occurs in a program when it allocates memory dynamically but fails to release or deallocate that memory properly.
    • As a result, the program continues to consume memory unnecessarily, leading to a gradual loss of available memory.

    27. What is the Observer Pattern?


    The Observer Pattern is a behavioral design pattern where an object, known as the subject, maintains a list of its dependents, called observers, that are notified of any state changes. This pattern is used to implement distributed event handling systems, ensuring that changes to one object trigger appropriate updates in dependent objects.

    28. Define Reflection in OOP.


    Reflection in OOP refers to the ability of a program to inspect and modify its structure at runtime. It allows a program to examine and manipulate its classes, methods, fields, and other elements dynamically. Reflection is commonly used for creating generic code, implementing plugins, or performing debugging and analysis tasks.

    29. What is the Open/Closed Principle?


    The Open/Closed Principle is one of the SOLID principles and states that software entities (classes, modules, functions) should be open for extension but closed for modification. This means that the behavior of a module can be extended without modifying its source code. 

    30. Define Factory Method Pattern.


    • The Factory Method Pattern is a creational design pattern that defines an interface for creating an object but allows subclasses to alter the type of objects that will be created.
    • It involves creating an interface or an abstract class for creating objects and letting the subclasses decide which class to instantiate. 

    31. Define Mutex.


    A Mutex (Mutual Exclusion) is a synchronization primitive used in concurrent programming to prevent multiple threads from accessing shared resources simultaneously. It ensures that only one thread can access the critical section at a time, avoiding data corruption.

    32. Explain the Adapter Design Pattern.


    • The Adapter Design Pattern is a structural pattern that allows the interface of an existing class to be used as another interface.
    • It acts as a bridge between incompatible interfaces, enabling them to work together.

    33. Explain the Template Method Pattern.


    The Template Method Pattern is a behavioural design pattern that defines the skeleton of an algorithm in the superclass but allows subclasses to alter certain steps of the algorithm without changing its structure. It promotes code reusability and flexibility.

    34. What is a Virtual Destructor?


    • A virtual destructor in C++ is a destructor declared with the ‘virtual’ keyword in the base class.
    • It ensures that the destructors of derived classes are properly invoked when deleting a base class pointer, preventing memory leaks.

    35. Define Smart Pointers in C++.


    Smart pointers in C++ are objects that manage the memory of dynamically allocated objects. They provide automatic memory management by handling the allocation and deallocation of memory, reducing the risk of memory leaks and making code more robust and readable.

    Course Curriculum

    Get Hand-on Experience from Java Training Course By IT Experts

    Weekday / Weekend BatchesSee Batch Details

    36. What is the Diamond Operator in Java?


    • The Diamond Operator (‘<>’) in Java is used for type inference when instantiating generic classes.
    • It allows developers to create instances without explicitly specifying the generic type, improving code readability.

    37. Explain the Strategy Design Pattern.


    The Strategy Design Pattern is a behavioural design pattern that provides a systematic way to define a family of algorithms, encapsulate each algorithm, and make them interchangeable. This pattern allows a client to choose an algorithm dynamically at runtime, promoting flexibility and maintainability in the system’s design.

    38. Define Composition Over Inheritance.


    Composition Over Inheritance is a fundamental design principle in OOP that suggests favouring object composition (building relationships between classes) over class inheritance when creating reusable and maintainable software.

    39. What is Method Chaining in OOP?


    Method chaining, also known as fluent interface or cascading, is a programming technique in OOP where multiple methods are called on an object in a single, continuous line. Each method returns the object itself, allowing subsequent methods to be invoked on the same object. This style enhances code readability and conciseness, making the code more expressive and reducing the need for temporary variables. 

    40. Explain Shallow Copy vs. Deep Copy.


    Shallow copy creates a new object but only copies the references to the data of the original object. In contrast, deep copy creates a new object and recursively copies all the contents, ensuring that the copied object is fully independent of the original. 

    41. Define the Law of Demeter.


    The Law of Demeter (LoD) is a design principle in OOP that encourages loose coupling between objects by limiting their interactions. According to LoD, an object should only communicate with its immediate neighbors and should not have knowledge of the internal workings of other objects. This principle promotes encapsulation, reducing dependencies between classes and enhancing the maintainability of the codebase.

    42. What is RAII (Resource Acquisition Is Initialization)?


    • RAII is a programming paradigm that ties the lifecycle of a resource, such as memory allocation or file handling, to the scope of an object.
    • In languages like C++ with deterministic destructors, resources are acquired during object initialization and released during object destruction.

    43. Explain the Proxy Design Pattern.


    The Proxy Design Pattern is a structural pattern that involves creating a surrogate or placeholder object to control access to another object.  Acting as an intermediary, the proxy can add additional functionality such as lazy loading, access control, or logging without altering the core behavior of the original object.

    44. Define Coercion in OOP.


    • Coercion in OOP refers to the automatic conversion of one data type to another, often performed implicitly by the programming language. 
    • Coercion is a feature designed to handle type compatibility and facilitate operations involving different data types without requiring explicit conversion by the programmer.

    45. Explain the Memento Design Pattern.


    The Memento Design Pattern is a behavioral pattern that enables an object to capture and externalize its internal state, allowing the object to be restored to this state later. This pattern consists of three main components: the Originator (the object whose state needs to be saved), the Memento (an object representing the state of the Originator), and the Caretaker (an object responsible for storing and managing multiple states of the Originator).

    46. What is the Null Object Pattern?


    • The Null Object Pattern is a behavioral design pattern that addresses the challenges of handling null references in a more systematic way.
    • Instead of using explicit null checks, the pattern introduces a special NullObject class that provides default or neutral behavior for the absence of a real object.

    47. Define the Mediator Design Pattern.


    The Mediator Design Pattern is a behavioral pattern that promotes loose coupling by centralizing communication between a set of objects through a mediator. The mediator encapsulates the interactions between objects, reducing direct dependencies among them. 

    48. What is the Visitor Design Pattern?


    • The Visitor Design Pattern is a behavioral pattern that represents an operation to be performed on the elements of an object structure.
    • It allows defining new operations without changing the classes of the elements on which it operates. 

    49. Explain the Decorator Design Pattern.


    The Decorator Design Pattern is a structural pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. It involves creating a set of decorator classes that are used to wrap concrete components. Decorators add or override functionalities of the original object transparently, providing a flexible and modular way to extend behavior. 

    50. Explain the Flyweight Design Pattern.


    • The Flyweight Design Pattern is a structural pattern that minimizes memory usage or computational expenses by sharing as much as possible with related objects. 
    • It involves dividing an object’s state into intrinsic (shared) and extrinsic (context-specific) parts.

    51. What is the State Design Pattern?


    The State Design Pattern is a behavioural pattern that allows an object to alter its behaviour when its internal state changes. It involves defining a set of state classes, each representing a different state of the object and allowing the object to transition from one state to another. This pattern encapsulates the state-specific behaviour into separate classes, making it easier to add new states or modify existing ones without modifying the object’s code.

    52. Define the Composite Design Pattern.


    • The Composite Design Pattern is a structural pattern that composes objects into tree structures to represent part-whole hierarchies.
    •  It allows clients to treat individual objects and compositions of objects uniformly. 

    53. Explain the Command Design Pattern.


    The Command Design Pattern is a behavioural pattern that encapsulates a request as an object, thereby allowing for the parameterization of clients with different requests, queuing of requests, and support for undoable operations. It involves defining a command interface with an execute method and concrete command classes that implement this interface.

    54. What is the Prototype Design Pattern?


    • The Prototype Design Pattern involves creating new objects by copying an existing object, known as the prototype. 
    • It is a creational pattern that aims to avoid the overhead of creating new objects using constructors.

    55. Define the Chain of Responsibility Pattern.


    The Chain of Responsibility Pattern is a behavioral pattern that allows a set of handlers to process requests sequentially. Each handler in the chain decides either to process the request or pass it to the next handler. This pattern decouples senders and receivers of requests, offering a flexible way to handle requests and allowing different handlers to contribute to the processing of a request.

    Course Curriculum

    Best Practical Java Training By Certified Experts

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

    56. What are some advantages of using OOPs?


    • Modularity
    • Reusability
    • Maintenance and Scalability
    • Encapsulation
    • Code Organization

    57. What is Dependency Injection?


    Dependency Injection (DI) is a design pattern and a technique in which the dependencies of a class (such as services, objects, or configurations) are injected from the outside rather than being created within the class. This promotes loose coupling, modular design, and testability, as classes can be easily replaced or configured with different dependencies without modifying their code.

    58. What are the various types of inheritance?


    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance

    59. What is Compile time Polymorphism?


    Compile-time polymorphism, also known as static polymorphism or method overloading, occurs when multiple methods in the same class have the same name but different parameters (number or type). Based on the method signature, the proper method to run is identified at compile time.

    • public class Calculator {
    • public int add(int a, int b)
    • {
    • return a + b;
    • }
    • public double add(double a, double b) {
    • return a + b;
    • }
    • }

    60. What is a superclass?


    A superclass, also known as a parent class or base class, is a class from which other classes (subclasses) inherit properties and behaviors. The superclass provides a blueprint for the creation of subclasses. The features of the superclass are inherited by its subclasses, promoting code reuse and the establishment of a hierarchical relationship.

    61. Is it always essential to generate objects from classes?


    In object-oriented programming, the primary purpose of classes is to define a blueprint for objects. While it is not strictly essential to instantiate objects from classes in all programming paradigms, doing so is fundamental to the principles of OOP. Objects are instances of classes, and they encapsulate both data and behavior. Without creating objects, you cannot take advantage of the modularity, encapsulation, and other benefits that OOP provides.

    62. How much memory does a class use?


    • A class itself does not consume memory during runtime. Memory is allocated for objects created from the class. 
    • The size of an object depends on the data members it contains, any methods it has, and potential overhead due to the object’s internal representation in memory.

    63. What does “static polymorphism” mean?


    Compile-time polymorphism, often referred to as method overloading or static polymorphism, is the phenomenon where the method to be performed is decided upon at compile time. Method overloading, in which several methods inside a class have the same name but distinct arguments, is how this is accomplished.

    64. Are there any restrictions on inheritance?


    Yes, there are certain restrictions on inheritance in various programming languages:

    Diamond Problem: Ambiguity in multiple inheritance, especially in languages like C++.

    Access Control: Private members of a superclass may not be directly accessible in a subclass.

    Final Classes or Methods: Some languages allow declaring classes or methods as final, making them non-inheritable or non-overridable.

    65. What does “dynamic polymorphism” mean?


    When the method to be performed is decided at runtime, this is known as dynamic polymorphism, often referred to as runtime polymorphism or method overriding. The process of providing a custom implementation for a method that is already defined in its superclass by a subclass is known as method overriding.

    66. What is the distinction between overloading and override?


    Overloading: Occurs within the same class when multiple methods have the same name but different parameters (either different types or a different number of parameters).

    Override: Involves providing a specific implementation for a method in a subclass that is already defined in its superclass. It is a way to achieve dynamic polymorphism.

    67. How does data abstraction happen?


    • Data abstraction is the technique of displaying only the pertinent aspects of an object while concealing the intricate implementation details. 
    • Encapsulation, in which an object’s internal workings are concealed and just its public interface is shown, is used to accomplish this.

    68. What does it mean to collect garbage in the realm of OOPs?


    Garbage collection is a process in which the programming language automatically reclaims memory occupied by objects that are no longer in use or reachable by the program. In OOP, when objects are created dynamically, it’s the responsibility of the garbage collector to identify and reclaim memory from objects that are no longer referenced by the program.

    69. What are access specifiers, and why are they important?


    • Access specifiers (e.g., public, private, protected) define the visibility and accessibility of class members (variables and methods). 
    • They play a crucial role in encapsulation, determining which parts of a class are accessible from outside the class.

    70. Can we run a Java program without implementing OOPs?


    In Java, the language itself is designed around the principles of object-oriented programming. Even if a Java program doesn’t explicitly define its classes and objects, it still relies on the fundamental OOP concepts provided by the language. The ‘main’ method, which is the entry point for Java applications, is typically part of a class, and objects are implicitly created during program execution.

    OOPS Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    71. Define the virtual functions.  


    In the context of polymorphism, virtual functions stand out as a key concept in languages like C++. A virtual function is a member function in a base class that is marked with the ‘virtual’ keyword. This designation allows derived classes to override the function, enabling dynamic binding and facilitating the execution of the appropriate method based on the actual type of the object during runtime.

    72. What’s the distinction between a base and a superclass?


    • “Base class” is a more general term, referring to any class in an inheritance hierarchy.
    • “Superclass” specifically denotes the parent class from which a particular class inherits.

    73. What are constructors?


    Constructors serve as essential components in the instantiation of objects. They are special methods within a class, sharing the same name as the class itself. Constructors are responsible for initializing the state of objects, and they come in various forms, including default constructors, parameterized constructors, and copy constructors. 

    74. List the limits of object-oriented programming. 


    • Complexity in large-scale systems.
    • Performance overhead due to abstraction.
    • Difficulty in modeling certain real-world scenarios.
    • Limited support for parallel processing.

    75. What is a copy constructor?


    A copy constructor is a specialized form of constructor that plays a vital role in creating a new object as a replica of an existing object. It involves copying the values and attributes of the source object to the newly created object, providing a mechanism for efficient object duplication.

    76. What are the different sorts of constructors?


    Default Constructor: Takes no parameters.

    Parameterized Constructor: Accepts parameters.

    Copy Constructor: Creates an object by copying an existing object.

    77. What is the access modifier for methods defined within an interface?


    In interfaces, methods are implicitly public and abstract in Java. This means that they are accessible from outside the interface, and any class implementing the interface must provide an implementation for these methods. The public access modifier ensures that these methods are part of the interface’s public contract.

    78. Name three operators that cannot be overloaded.


    • ‘::’ (Scope Resolution Operator)
    • ‘.’ (Member Access Operator)
    • ‘.*’ (Pointer to Member Operator)

    79. How does encapsulation differ from data abstraction?


    Encapsulation: Bundling data and methods that operate on the data into a single unit (class), and restricting access to certain components.

    Data Abstraction: Hiding the complex implementation details and exposing only the essential features of an object.

    80. What is the purpose of ‘finalize’?


    • In Java, ‘finalize’ is a method called by the garbage collector before an object is reclaimed.
    • It allows an object to perform cleanup operations before being deallocated.

    81. What is the try/catch block?


    The try/catch block is used in exception handling to enclose code that might throw an exception. The catch block specifies how to handle the exception if it occurs, allowing the program to gracefully respond to unexpected situations.

    82. What’s the difference between OOP and SOP?


    OOP (Object-Oriented Programming): A programming paradigm that uses objects, classes, and principles like encapsulation, inheritance, and polymorphism.

    SOP (Structured Programming): A programming paradigm emphasizing structured control flow with procedures or functions.

    83. What are the properties of an abstract class?


    • Can have abstract and concrete methods.
    • Cannot be instantiated.
    • Can have constructors.
    • Can have fields (variables).

    84. What is the definition of a final variable?


    When a variable is defined with the “final” keyword, it means that once it is initialised, its value cannot be altered. Once allocated, it stays that way for the duration of the programme.

    85. What actually is coupling in OOP?


    • Coupling refers to the degree of dependency between different components or classes in a system.
    • Low coupling is desirable as it promotes modularity and easier maintenance.
    • High coupling can lead to a lack of flexibility and increased complexity in the codebase.

    86. What’s known as constructor chaining?


    Constructor chaining refers to the practice of calling one constructor from another within the same class. This enables the reuse of code and initialization logic. It allows constructors with different parameters or levels of complexity to call each other, ensuring that common initialization steps are shared across various constructors in a class.

    87. What exactly is an exception?


    • An exception is a sudden occurrence or mistake that prevents a programme from operating as intended.
    • It can happen during runtime, and in order to keep the programme from terminating, it needs to be handled properly.

    88. What are the various levels of data abstraction?


    Physical Level: Describes how data is stored in the database, including details like data structures, file formats, etc.
    Logical Level: Represents data without specifying how it’s stored, focusing on relationships, constraints, and business rules.
    View Level: Provides a user-specific view of the data, presenting a subset or combination of data from the logical level.

    89. What is the distinction between error and exception?


    Errors are severe issues that typically cannot be handled by the program. They often indicate critical problems that compromise the stability and functionality of the entire system.
    Exceptions are events that occur during the execution of a program but can be handled through proper exception handling mechanisms. They do not necessarily lead to program termination.

    90. What’s known as OOP Cohesion?


    OOP Cohesion refers to the degree to which the elements (methods and attributes) within a class or module are related to each other and contribute to a single, well-defined purpose. High cohesion is desirable, as it promotes maintainability and readability by keeping related functionalities together.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free