Object-Oriented Programming (OOPs) is a fundamental concept in modern software development that helps organize code in a more modular, reusable, and maintainable way.
Here we have shared Top OOPs interview questions and answers specifically designed for professional level interviews and discussions. Instead of basic or textbook definitions, these questions focus on real-world scenarios, comparisons, and design decisions that hiring managers, HR professionals, and technical leads often explore during interviews.
Also We have added language-specific OOPs questions for Java, Python, PHP, C++, and C#, including code based challenges, behavioral patterns, and comparisons to explain differences clearly. These are tailored to help you prepare confidently for interviews that test deep OOPs knowledge in practical applications
Table of Contents
Top OOPs Interview Questions and Answers
Lets start with Top OOPs Interview Questions and Answers, that experienced interviewers and hiring managers ask most.
Que 1. How do design patterns complement object-oriented principles in enterprise architecture?
Design patterns provide proven templates that solve common software design problems. When used with OOP principles like inheritance, polymorphism, and encapsulation, they enhance code reusability, testability, and system extensibility. For instance, the Strategy Pattern allows runtime polymorphism without altering existing code.
Que 2. How can object-oriented design be evaluated for maintainability?
Object-oriented design is evaluated for maintainability through metrics such as coupling, cohesion, depth of inheritance, and class responsibility. Highly cohesive and loosely coupled classes lead to more maintainable systems. Using tools like SonarQube can help quantify these metrics.
Que 3. What are the pitfalls of deep inheritance hierarchies, and how can they be avoided?
Deep inheritance trees can lead to fragile codebases, tight coupling, and difficulty in unit testing. They can be avoided by favoring composition over inheritance and adhering to the Liskov Substitution Principle, ensuring subclasses can replace parent classes without altering expected behavior.
Que 4. How do you model real-world entities using abstraction in OOP?
Abstraction involves identifying the essential characteristics of an object while hiding its complex details. In real-world modeling, classes abstract behavior and properties relevant to the domain while exposing only necessary methods. For example, a PaymentProcessor
interface might abstract multiple payment gateways.
Que 5. How do access modifiers support encapsulation and security in OOP?
Access modifiers (private
, protected
, public
, etc.) control the visibility of class members, enforcing encapsulation. By restricting access to internal class logic, they prevent external components from manipulating object state inappropriately, thus securing and stabilizing the system.
Que 6. What’s the difference between abstract classes and interfaces in a large-scale system?
Feature | Abstract Class | Interface |
---|---|---|
Inheritance | Single | Multiple |
Implementation | Can have method implementations | No implementation (prior to C# 8) |
Use Case | When base functionality is required | When behavior contracts are needed |
Abstract classes provide partial implementations, while interfaces are ideal for defining polymorphic contracts across unrelated classes.
Que 7. How do you implement OOP principles in microservices architecture?
In microservices, OOP is implemented inside service boundaries. Each service encapsulates its domain logic using OOP principles like abstraction and encapsulation. Additionally, DDD (Domain-Driven Design) encourages modeling bounded contexts with object-oriented entities and value objects.
Que 8. How does the Open/Closed Principle apply to real-world applications?
The Open/Closed Principle ensures that systems are open to extension but closed to modification. For example, a reporting system can support new report types by introducing new classes without altering existing logic. This minimizes risk and improves flexibility.
Que 9. What are virtual methods and how do they relate to runtime polymorphism?
Virtual methods are declared in a base class and overridden in derived classes. This enables polymorphic behavior at runtime, allowing objects to decide which method to invoke depending on the object’s actual type.
Que 10. How does dependency injection support object-oriented design?
Dependency Injection (DI) decouples class dependencies by injecting them at runtime rather than hardcoding. This supports the Dependency Inversion Principle and enhances testability, reusability, and flexibility.
Que 11. How do you apply the Interface Segregation Principle in a layered application?
Instead of one large interface, ISP advocates splitting into smaller, client-specific interfaces. For example, in a user management system, separate interfaces for IUserReader
, IUserWriter
, and IUserNotifier
can avoid forcing clients to implement unnecessary methods.
Que 12. What is method overloading vs method overriding in a polymorphic system?
Method overloading allows multiple methods with the same name but different parameters in the same class. Overriding means redefining a base class method in a derived class. Overriding supports runtime polymorphism, whereas overloading supports compile-time polymorphism.
Que 13. How can you prevent memory leaks in OOP-based applications?
Memory leaks occur when objects are held in memory unnecessarily. To prevent them:
- Unsubscribe event handlers
- Avoid static references to large objects
- Use
IDisposable
andusing
blocks properly - Implement weak references when necessary
Que 14. What is the role of constructors in object-oriented programming?
Constructors initialize new objects and define initial states. Overloaded constructors support different initialization paths. In DI contexts, constructors also receive external dependencies.
Que 15. How would you model polymorphic behavior using interfaces?
Polymorphic behavior is modeled by defining an interface and letting multiple classes implement it differently. The consumer uses the interface without knowing the concrete class, promoting loose coupling.
public interface IFormatter {
string Format(string data);
}
public class JsonFormatter : IFormatter {
public string Format(string data) => $"{{\"data\":\"{data}\"}}";
}
Que 16. How can reflection be dangerous in OOP-based applications?
Reflection allows runtime type discovery and method invocation but can break encapsulation and reduce performance. Overuse may lead to security vulnerabilities and unstable code, especially when accessing private members.
Que 17. What is an anti-pattern in object-oriented design?
Common OOP anti-patterns include:
- God Object (too much responsibility)
- Circular Dependency
- Inappropriate Intimacy (tight coupling)
Avoiding these improves code quality and maintainability.
Que 18. How do you apply inheritance without violating encapsulation?
Inheritance should not expose internal details of the parent class. Using protected
sparingly and limiting visibility to internal logic helps. Prefer composition if encapsulation is at risk.
Que 19. What is a Domain Model, and how is it used in OOP?
A domain model represents business entities and logic in code. In OOP, each entity (like Order
, Invoice
) is modeled as a class with properties and methods, capturing both state and behavior.
Que 20. How would you implement lazy initialization in OOP?
Lazy initialization defers object creation until it’s actually needed. This is useful for resource-intensive objects.
private Lazy<HeavyService> _service = new(() => new HeavyService());
public HeavyService Service => _service.Value;
Que 21. What is cohesion in OOP and why is it important?
Answer:
Cohesion refers to how closely related and focused the responsibilities of a class are. High cohesion means a class is designed to do one thing and do it well, making the code easier to maintain and test. Low cohesion indicates a class is trying to do too many unrelated tasks, which can lead to poor design and difficulty in debugging. In object-oriented design, high cohesion is considered a best practice as it promotes modularity and reusability.
Que 22. How does favoring composition over inheritance improve system design?
Answer:
Favoring composition over inheritance allows for more flexible and maintainable designs. Composition enables you to build complex behaviors by combining simpler objects, while inheritance tightly couples the child class to the parent class. With composition, changes in one class do not propagate unwanted side effects in other classes, making systems easier to extend or modify.
Que 23. How do you detect and fix tight coupling in OOP?
Answer:
Tight coupling occurs when classes are heavily dependent on one another. This can be detected when changes in one class frequently break another. To fix this, use dependency injection, interfaces, or event-driven programming to reduce direct dependencies. Aim to communicate through abstractions rather than concrete implementations.
Que 24. What is encapsulation leakage and how can it be avoided?
Answer:
Encapsulation leakage happens when the internal details of a class are exposed outside its interface, such as returning a reference to an internal list. It can be avoided by returning copies of objects, using unmodifiable views, and strictly controlling access using private or protected modifiers.
Que 25. How can SOLID principles be applied to real-world applications?
Answer:
SOLID principles (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion) guide the creation of maintainable and scalable systems. For example:
- SRP: Separate user management from billing logic.
- OCP: Add new payment types without modifying existing payment logic.
- LSP: Subclasses like
CreditCardPayment
should replacePaymentMethod
without breaking functionality. - ISP: Divide interfaces like
Printable
,Scannable
. - DIP: Inject dependencies using constructors or frameworks like Spring.
Que 26. What is a marker interface and when would you use one?
Answer:
A marker interface is an interface with no methods or constants. It is used to mark a class for special behavior, like Serializable
in Java. The compiler or runtime uses the presence of such interfaces to apply special processing rules.
Que 27. What’s the difference between passive and active objects in OOP?
Answer:
Passive objects store data and offer getters/setters, often called POJOs (Plain Old Java Objects). Active objects contain both data and behavior and can initiate actions. Using active objects helps encapsulate behavior, reducing logic scattered across the system.
Que 28. How does OOP help with multithreading challenges?
Answer:
OOP supports multithreading by encapsulating synchronization logic within objects, allowing shared resources to manage their own access. Proper use of synchronized methods, thread-safe classes, and avoiding shared mutable state enhances concurrency safety.
Que 29. What is a mixin and how is it used in object-oriented languages?
Answer:
A mixin is a class that offers functionality to other classes through composition rather than inheritance. Languages like Python support mixins through multiple inheritance. Mixins promote code reuse while avoiding the pitfalls of deep inheritance trees.
Que 30. How do design patterns like Strategy and Observer relate to OOP principles?
Answer:
The Strategy pattern promotes the Open/Closed Principle by allowing behavior to be selected at runtime. The Observer pattern encourages loose coupling and abstraction, aligning with Dependency Inversion. Both patterns leverage polymorphism and composition, foundational OOP concepts.
Que 31. What’s the difference between behavioral and structural patterns in OOP?
Answer:
Behavioral patterns manage communication between objects (e.g., Strategy, Observer), focusing on runtime behavior. Structural patterns (e.g., Adapter, Composite) deal with class composition and object relationships, focusing on how objects are assembled.
Que 32. How does the Template Method pattern promote reuse in OOP?
Answer:
The Template Method pattern defines the skeleton of an algorithm in a superclass and allows subclasses to override specific steps. This promotes reuse of the common structure while allowing customization of parts, adhering to the Open/Closed Principle.
Que 33. How is OOP applied in real-time systems like robotics or gaming?
Answer:
In real-time systems, OOP is used to model components as objects—like sensors, motors, or characters—each encapsulating state and behavior. Polymorphism enables behavior switching based on context, while inheritance promotes code reuse for similar entities.
Que 34. What are immutable objects and why are they important in OOP?
Answer:
Immutable objects cannot be changed after creation. They simplify concurrency by making shared state thread-safe and reduce side effects. Examples include Java’s String
or Python’s tuple
. Use immutability to build predictable, robust systems.
Que 35. How do functional programming concepts integrate with OOP?
Answer:
Modern OOP languages incorporate functional features like lambdas, higher-order functions, and immutability. These features allow you to write concise, declarative code within an OOP framework. For example, Java 8 streams offer functional-style collection processing.
Que 36. How does the Visitor pattern work in an object-oriented system?
Answer:
The Visitor pattern separates algorithms from object structures. It allows adding new operations without modifying the classes of the elements. It’s especially useful when working with object hierarchies where new behavior needs to be added frequently.
Que 37. How do you implement a singleton class, and what are its drawbacks?
Answer:
A singleton ensures only one instance of a class exists. In Java, this can be done using a private constructor and a static method. Drawbacks include difficulty in unit testing and tight coupling. Use dependency injection frameworks to manage lifecycle more cleanly.
Que 38. What is the Liskov Substitution Principle and how does it prevent design flaws?
Answer:
The Liskov Substitution Principle (LSP) states that subclasses must be replaceable with their base classes without affecting functionality. Violations of LSP—like overriding methods in a way that breaks expected behavior—can introduce bugs and reduce reusability.
Que 39. What is dynamic dispatch and how does it enable polymorphism?
Answer:
Dynamic dispatch is the process by which a call to an overridden method is resolved at runtime. This enables runtime polymorphism, allowing behavior to be determined based on the actual object type, not the reference type.
Que 40. How can interface-based design improve testability in OOP?
Answer:
Interface-based design allows for easy mocking and substitution in unit tests. By depending on abstractions rather than implementations, systems become more modular, and individual components can be tested in isolation.
Que 41. How does method chaining work and when is it useful in OOP?
Answer:
Method chaining is a design pattern where methods return the current object, allowing multiple method calls to be chained in a single statement. It is commonly used in builder patterns and fluent interfaces to improve readability.
Que 42. What is the Law of Demeter and how does it apply to OOP?
Answer:
The Law of Demeter (LoD) states that an object should only communicate with its immediate friends. Avoid calling methods on returned objects of other objects (a.getB().getC().doSomething()
). This improves encapsulation and reduces coupling.
Que 43. How do you implement event-driven architecture using OOP?
Answer:
Use the Observer pattern or event listeners to implement event-driven architecture. Objects subscribe to events and get notified when they occur, allowing decoupled communication between components. This is common in GUI applications and microservices.
Que 44. What are the trade-offs of using interfaces over abstract classes?
Answer:
Interfaces offer more flexibility and support multiple inheritances of type, while abstract classes allow code reuse via method implementations. Use interfaces for contract definition and abstract classes when shared behavior is needed.
Que 45. How does OOP help in building scalable software?
Answer:
OOP enables scalability by promoting modular, reusable, and loosely coupled components. As requirements grow, new functionality can be added with minimal changes to existing code, reducing risk and effort during scaling.
Que 46. What is a fluent interface and how does it relate to OOP?
Answer:
A fluent interface uses method chaining to make the code more readable and expressive. It is implemented by returning this
from each method. Fluent interfaces often appear in builders or configuration APIs, aligning with encapsulation and usability principles.
Que 47. How does OOP help in implementing domain-driven design (DDD)?
Answer:
OOP models real-world entities using classes, aligning closely with DDD, where each domain concept is represented as an object. Entities, value objects, and aggregates map naturally to OOP constructs, promoting clarity and maintainability.
Que 48. What is a bounded context in OOP systems?
Answer:
A bounded context defines the boundary within which a specific model applies. In OOP, it helps limit the scope of object interactions and prevents ambiguity. Each context can have its own version of the same concept (e.g., Order
in sales vs. billing).
Que 49. How do you prevent object mutation in complex systems?
Answer:
Use immutability, private constructors, and final fields. Use builder patterns to construct complex objects safely. Libraries and language features like readonly
in C#, val
in Kotlin, and @Immutable
in Groovy can also help.
Que 50. How does OOP support the principle of least privilege?
Answer:
By using access modifiers like private
, protected
, and public
, OOP enforces the principle of least privilege, ensuring that only necessary parts of the code have access to internal object data, reducing security risks and improving encapsulation.

Also Check: Software Engineer Interview Questions and Answers
Java OOPs Interview Questions and Answers
Que 51. How does Java handle object slicing in inheritance?
Java doesn’t allow object slicing the way C++ does because Java handles all non-primitive objects through references. When assigning a subclass object to a superclass reference, only the reference is changed — the object remains intact in memory. However, subclass-specific methods will no longer be accessible unless the reference is cast back.
Que 52. In Java, how do anonymous classes relate to OOP principles?
Anonymous classes in Java support encapsulation and polymorphism by allowing the creation of short-lived class instances for one-time use. They’re often used to implement interfaces or extend classes on-the-fly, particularly in event handling or strategy patterns.
Runnable r = new Runnable() {
public void run() {
System.out.println("Running anonymously");
}
};
Que 53. How do Java records support immutability in object-oriented design?
Java Records, introduced in Java 14, are immutable data carriers. They provide a concise syntax for declaring immutable objects with built-in support for value-based equality, encapsulation, and thread safety — ideal for modeling DTOs and functional-style designs.
Que 54. What’s the impact of final methods and classes in polymorphic systems?
Declaring methods as final
in Java prevents them from being overridden, enforcing strict inheritance contracts. Declaring classes as final
blocks subclassing altogether, useful when you want to guarantee a class’s behavior remains unchanged, such as with security or utility classes.
Que 55. How does Java support multiple inheritance of behavior?
While Java does not support multiple inheritance of classes, it allows multiple inheritance of behavior through interfaces. With default methods (Java 8+), interfaces can provide method implementations, enabling shared behavior while avoiding diamond problem complexity.
Que 56. How do Java inner classes promote encapsulation?
Java inner classes (member, static, local, and anonymous) allow logically grouping classes together. This helps encapsulate helper functionality that’s only relevant within the outer class, improving cohesion and reducing visibility of implementation details.
Que 57. Can you explain the difference between shallow and deep cloning in Java OOP?
Shallow cloning copies object references, not the actual nested objects, which can lead to unexpected mutations. Deep cloning recursively clones all referenced objects to ensure complete independence between original and copied instances.
Que 58. How does Java achieve runtime polymorphism, and how is it internally handled?
Java uses dynamic method dispatch to achieve runtime polymorphism. The JVM uses the virtual method table (vtable) associated with each class to determine the actual method to invoke based on the object’s runtime type rather than compile-time reference.
Que 59. What’s the difference between composition and aggregation in Java OOP?
Composition implies a strong ownership where the child object cannot exist without the parent. Aggregation is a weaker association where the child can exist independently. Both are used for structuring complex objects but have different lifecycle implications.
Que 60. How do annotations reflect OOP principles in Java?
Annotations support abstraction and meta-programming in Java. By defining behaviors externally and declaratively, they encapsulate logic away from class implementations, promote cleaner code, and are heavily used in frameworks like Spring and Hibernate to inject behaviors dynamically.
More Questions here: Java OOPs Interview Questions with PDF
Python OOPs Interview Questions and Answers
Que 61. How is method overloading handled in Python since it doesn’t support it natively?
Python does not support traditional method overloading like Java or C#. Instead, developers simulate it using default arguments, variable-length arguments (*args
, **kwargs
), or function dispatchers like functools.singledispatch
.
def greet(name=None):
if name:
print(f"Hello, {name}")
else:
print("Hello")
greet()
greet("Alice")
Que 62. What are the differences between @classmethod, @staticmethod, and instance methods in Python?
Method Type | Access to Class (cls ) | Access to Instance (self ) | Use Case |
---|---|---|---|
Instance Method | No | Yes | Modify/read instance data |
Class Method | Yes | No | Factory methods, modifying class state |
Static Method | No | No | Utility methods without instance/class dependency |
Que 63. How does Python support encapsulation and how is it enforced?
Python supports encapsulation using naming conventions rather than strict access modifiers:
_protected_var
: for internal use (not enforced)__private_var
: name mangling to discourage external access
Still, all variables are accessible due to Python’s philosophy of “we are all consenting adults here.”
Que 64. Explain how polymorphism is implemented in Python.
Polymorphism in Python is implicit and based on duck typing. As long as different classes implement the expected method, they can be used interchangeably.
class Dog:
def speak(self): return "Woof"
class Cat:
def speak(self): return "Meow"
def animal_sound(animal):
print(animal.speak())
animal_sound(Dog())
animal_sound(Cat())
Que 65. How does Python implement abstraction?
Python provides abstraction using abstract base classes (ABCs) in the abc
module.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self): pass
class Dog(Animal):
def speak(self): return "Woof"
This ensures that derived classes must implement the abstract methods.
Que 66. What are dunder methods and how do they support OOP?
Dunder methods (like __init__
, __str__
, __add__
) are Python’s way of operator overloading and enabling OOP constructs like object initialization, comparison, iteration, etc.
class Vector:
def __init__(self, x, y): self.x, self.y = x, y
def __add__(self, other): return Vector(self.x + other.x, self.y + other.y)
Que 67. How do composition and inheritance differ in Python OOP?
Inheritance models “is-a” relationships, while composition models “has-a” relationships.
class Engine: pass
class Car:
def __init__(self):
self.engine = Engine() # composition
Inheritance allows reusing behaviors, but composition allows flexible structuring and reduces coupling.
Que 68. What is the role of metaclasses in Python OOP?
Metaclasses control the creation of classes. They allow modifying class behavior or injecting logic during class creation, similar to class factories or interceptors.
class Meta(type):
def __new__(cls, name, bases, dct):
dct['class_name'] = name
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta): pass
Que 69. How does Python implement multiple inheritance and resolve method conflicts?
Python supports multiple inheritance and uses the C3 linearization algorithm (MRO – Method Resolution Order) to resolve conflicts.
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
print(D.__mro__)
Use super()
cautiously to ensure correct method resolution.
Que 70. Can you implement interface-like behavior in Python?
Yes. Although Python doesn’t have interfaces like Java, you can achieve the same effect using abstract base classes (ABCs) or simply duck typing. Interfaces in Python are more about method presence than type declarations.
More Questions here: Python OOPs Interview Questions
C# OOPs Interview Questions and Answers
Que 71. How does C# implement encapsulation, and how is it enforced?
C# uses access modifiers like private
, protected
, internal
, and public
to enforce encapsulation. This controls how class members are exposed.
public class BankAccount
{
private decimal balance;
public void Deposit(decimal amount)
{
if (amount > 0)
balance += amount;
}
public decimal GetBalance() => balance;
}
Encapsulation ensures data integrity by restricting direct access.
Que 72. Explain how polymorphism works in C# with an example.
C# supports compile-time (method overloading) and runtime (method overriding) polymorphism.
public class Animal
{
public virtual void Speak() => Console.WriteLine("Some sound");
}
public class Dog : Animal
{
public override void Speak() => Console.WriteLine("Bark");
}
At runtime, the method call is resolved based on the actual object type.
Que 73. How is abstraction achieved in C#?
Abstraction is achieved using abstract classes and interfaces. These define method signatures without implementation.
public abstract class Shape
{
public abstract double Area();
}
Interfaces enforce contracts, while abstract classes allow partial implementation.
Que 74. Compare abstract classes and interfaces in C#.
Feature | Abstract Class | Interface |
---|---|---|
Inheritance | Single | Multiple |
Implementation Allowed | Yes | No (until C# 8 default) |
Constructors | Yes | No |
Access Modifiers | Allowed | Not allowed (until C# 8) |
Que 75. What is object slicing and does C# suffer from it?
Object slicing occurs when an object of a derived class is assigned to a base class object, causing loss of derived-specific data.
C# avoids this by using references rather than object copies, unlike C++. So, object slicing isn’t typically an issue in C#.
Que 76. How does inheritance impact maintainability in C# projects?
While inheritance promotes code reuse, deep inheritance hierarchies can lead to tight coupling and poor maintainability. Prefer composition over inheritance when:
- Shared behavior is minimal.
- You need more flexibility at runtime.
Que 77. What are virtual, override, and new keywords in C# OOP?
virtual
: allows a base class method to be overridden.override
: modifies a virtual method in the derived class.new
: hides the base class method without overriding.
public class Base { public virtual void Show() => Console.WriteLine("Base"); }
public class Derived : Base { public override void Show() => Console.WriteLine("Derived"); }
Que 78. How does C# achieve method overloading?
C# allows multiple methods with the same name but different parameter lists.
public void Log(string message) { }
public void Log(string message, int code) { }
Method overloading improves code clarity without requiring different method names.
Que 79. What is the role of constructors in OOP in C#?
Constructors initialize objects and support overloading and chaining.
public class Person
{
public string Name { get; }
public Person(string name) => Name = name;
}
Use base()
to call a parent constructor and this()
to chain within the same class.
Que 80. How is composition implemented in C# and why prefer it?
Composition is implemented by including objects of other classes as members. It’s preferred over inheritance when behavior doesn’t need to be shared across a hierarchy.
public class Engine { }
public class Car
{
private Engine _engine = new Engine();
}
Why perfer it:
- Lower coupling
- Better flexibility
- Easier unit testing
More Questions here: C# OOPs Interview Questions and Answers PDF
C++ OOPs Interview Questions and Answers
Que 81. How is dynamic polymorphism implemented in C++?
Dynamic polymorphism in C++ is achieved using virtual functions. This enables method overriding where the function call is resolved at runtime.
class Animal {
public:
virtual void speak() { std::cout << "Animal sound\n"; }
};
class Dog : public Animal {
public:
void speak() override { std::cout << "Bark\n"; }
};
Calling speak()
on a base class pointer pointing to a Dog
object invokes the overridden version.
Que 82. What is the role of the virtual
keyword in C++ OOP?
The virtual
keyword tells the compiler to use dynamic dispatch for the method, enabling runtime polymorphism. It must be used in base class declarations to allow proper overriding.
Use cases:
- Method overriding
- Interface-like behavior via abstract base classes
- Avoiding object slicing
Que 83. How is multiple inheritance handled in C++ and what are the complications?
C++ allows multiple inheritance directly but it may lead to the Diamond Problem, where a derived class inherits from two classes that share a common base.
Solution: Use virtual inheritance to avoid ambiguity.
class A { };
class B : virtual public A { };
class C : virtual public A { };
class D : public B, public C { }; // Single A instance in D
Que 84. What is object slicing and how can it be avoided?
Object slicing occurs when a derived class object is assigned to a base class object by value, slicing off derived class data.
Avoid it by:
- Using references or pointers instead of object copying
- Marking base classes with virtual destructors
Que 85. How is encapsulation enforced in C++?
Encapsulation is implemented using access specifiers (private
, protected
, public
). It restricts direct access to internal object states.
class Account {
private:
double balance;
public:
void deposit(double amt) { if (amt > 0) balance += amt; }
double getBalance() { return balance; }
};
This promotes data security and integrity.
Que 86. Compare composition vs inheritance in C++ with examples
Feature | Inheritance | Composition |
---|---|---|
Reusability | Shares interface and behavior | Shares functionality via class members |
Coupling | Tighter coupling | Loose coupling |
Flexibility | Less flexible (compile-time) | More flexible (runtime possible) |
Example Use Case | “Is-a” relationship (Dog is an Animal) | “Has-a” relationship (Car has Engine) |
Que 87. How do constructors and destructors work in inheritance?
- Constructors are called from base to derived
- Destructors are called from derived to base
class Base {
public:
Base() { std::cout << "Base\n"; }
virtual ~Base() { std::cout << "Base destroyed\n"; }
};
class Derived : public Base {
public:
Derived() { std::cout << "Derived\n"; }
~Derived() { std::cout << "Derived destroyed\n"; }
};
Always declare base class destructors as virtual
for proper cleanup.
Que 88. What is a pure virtual function and when do you use it?
A pure virtual function is declared by assigning = 0
in the base class. It makes the class abstract, meaning you cannot instantiate it.
class Shape {
public:
virtual void draw() = 0;
};
Use it when the base class defines an interface but not implementation.
Que 89. How is function overloading different from overriding in C++?
- Overloading: Compile-time polymorphism; same function name, different parameters.
- Overriding: Runtime polymorphism; same signature in base and derived class.
class Example {
public:
void show(int x) { } // Overloading
virtual void print() { } // Can be overridden
};
Que 90. What are virtual destructors and why are they important in OOP?
Virtual destructors ensure that when an object is deleted via a base class pointer, the derived class destructor is also called.
class Base {
public:
virtual ~Base() { std::cout << "Base destroyed\n"; }
};
Without virtual destructors, resources from derived classes may not be properly released, leading to memory leaks.
PHP OOPs Interview Questions and Answers
Que 91. How is method overloading implemented in PHP, given that PHP does not support it natively?
PHP does not natively support method overloading like Java or C++. However, similar behavior can be mimicked using __call()
or __callStatic()
magic methods.
class Demo {
public function __call($name, $arguments) {
if ($name == 'test') {
if (count($arguments) == 1) {
return "Called with one argument: " . $arguments[0];
} elseif (count($arguments) == 2) {
return "Called with two arguments: " . implode(", ", $arguments);
}
}
}
}
$obj = new Demo();
echo $obj->test("A");
echo $obj->test("A", "B");
Que 92. What is the difference between abstract class and interface in PHP OOP?
Feature | Abstract Class | Interface |
---|---|---|
Method Type | Can have both abstract and concrete methods | Only abstract method signatures |
Properties | Can define variables with visibility | Only constants allowed (pre PHP 8.1) |
Inheritance | One abstract class per class | Multiple interfaces can be implemented |
Use abstract classes for partial implementation and interfaces for contracts.
Que 93. How does PHP implement polymorphism?
Polymorphism in PHP is achieved via method overriding using inheritance and interfaces.
interface Animal {
public function speak();
}
class Dog implements Animal {
public function speak() {
echo "Bark";
}
}
class Cat implements Animal {
public function speak() {
echo "Meow";
}
}
This allows different classes to implement the same interface in their own way.
Que 94. What is a trait in PHP and how is it different from inheritance?
Traits are used to enable code reuse in single inheritance languages like PHP. Unlike inheritance, traits are not part of the class hierarchy.
trait Logger {
public function log($msg) {
echo "Log: $msg";
}
}
class MyClass {
use Logger;
}
Traits resolve the issue where multiple inheritance is not supported.
Que 95. How is encapsulation implemented in PHP OOP?
Encapsulation is enforced using access modifiers: public
, protected
, and private
.
class Account {
private $balance = 0;
public function deposit($amt) {
if ($amt > 0) $this->balance += $amt;
}
public function getBalance() {
return $this->balance;
}
}
This restricts direct access to internal properties, promoting secure design.
Que 96. What are the magic methods in PHP and how are they used in OOP?
Magic methods in PHP are special methods prefixed with __
. Common ones in OOP include:
__construct()
– Constructor__destruct()
– Destructor__get()
,__set()
– Property overloading__call()
– Method overloading__clone()
– Custom clone behavior
They allow defining dynamic behavior for objects.
Que 97. Explain the use of final
keyword in PHP OOP.
The final
keyword prevents a method from being overridden or a class from being extended.
final class Core {}
class Utility {
final public function log() {
echo "Can't override this";
}
}
Use it to secure business logic or enforce specific behaviors.
Que 98. How is object cloning done in PHP?
Cloning is done using the clone
keyword. You can customize cloning using the __clone()
magic method.
class User {
public $name;
public function __clone() {
$this->name = "Clone of " . $this->name;
}
}
$u1 = new User();
$u1->name = "John";
$u2 = clone $u1;
Que 99. How does PHP OOP support dependency injection?
Dependency Injection (DI) allows injecting objects into classes to reduce tight coupling.
class Logger {
public function log($msg) { echo $msg; }
}
class Service {
private $logger;
public function __construct(Logger $logger) {
$this->logger = $logger;
}
}
You can inject via constructor, setter, or property.
Que 100. What is late static binding in PHP?
Late static binding allows referencing the called class in a context of static inheritance, using static::
instead of self::
.
class Base {
public static function who() {
echo static::class;
}
}
class Child extends Base {}
Child::who(); // Outputs "Child"
It resolves methods in the context of the calling class, not the defined class.

Also Check: PHP Interview Questions and Answers
OOPs Interview Questions PDF
Finding and accessing the questions and answers may be hard for last-minute revisions, so we have added questions to a PDF. You can download and save it for instant access anytime.
You can also explore more QnA guides on our platform. Best wishes for you next Interview.