Object-Oriented Programming Concepts MCQ
Test your Object-Oriented Programming knowledge with 100 multiple choice questions covering fundamentals to advanced concepts, with instant feedback and explanations.
How This Practice Test Works
Every question below expands right on this page — click a question to reveal its four options, pick the one you think is correct, and you'll get instant feedback along with the correct answer and a short explanation of the reasoning. Questions are grouped by difficulty, so start with the 40 beginner questions to confirm your fundamentals, work through the 40 intermediate ones, and finish with the 20 advanced questions that mirror what exams and technical screenings actually ask. There's no sign-up, no timer, and no limit — retake the test as often as you like.
Curated by Tech Baithak Editorial Team · Last updated: June 2026
1
What is a "class" in object-oriented programming?
Correct Answer
A blueprint or template for creating objects, defining their properties and behaviors
Explanation
A class defines the structure (attributes) and behavior (methods) that its objects will have, but is not itself an instance.
2
What is an "object" in object-oriented programming?
Correct Answer
An instance of a class, with its own state and behavior
Explanation
An object is a concrete instance created from a class, holding actual data in its attributes.
3
What does "encapsulation" mean in OOP?
Correct Answer
Bundling data and methods that operate on that data within one unit, restricting direct access to internals
Explanation
Encapsulation hides an object's internal state and requires interaction through well-defined methods, protecting data integrity.
4
What is "inheritance" in OOP?
Correct Answer
A mechanism where a new class derives properties and behaviors from an existing class
Explanation
Inheritance lets a subclass reuse and extend fields and methods from a parent (base) class, promoting code reuse.
5
What is "polymorphism" in OOP?
Correct Answer
The ability of different classes to be treated through the same interface, with each providing its own implementation
Explanation
Polymorphism allows objects of different types to respond to the same method call in ways appropriate to their own type.
6
What is "abstraction" in OOP?
Correct Answer
Hiding unnecessary implementation details and exposing only essential features of an object
Explanation
Abstraction focuses on what an object does rather than how it does it, simplifying complexity for the user of the object.
7
What is a "constructor"?
Correct Answer
A special method automatically called when an object is created, used to initialize its state
Explanation
Constructors set up initial values for an object's attributes at the moment the object is instantiated.
8
What is the term for a variable that belongs to an object (an instance of a class)?
Correct Answer
Instance variable (attribute)
Explanation
Instance variables hold data unique to each object; each object has its own copy, separate from other instances.
9
What is a "method" in OOP?
Correct Answer
A function defined inside a class that operates on objects of that class
Explanation
Methods define the behaviors of objects and typically access or modify the object's attributes.
10
In OOP, what is a "parent class" (or "base class")?
Correct Answer
The class from which other classes inherit properties and methods
Explanation
A parent class provides shared functionality that one or more child (derived) classes can inherit and extend.
11
What is a "child class" (or "derived class" / "subclass")?
Correct Answer
A class that inherits from another class and may add or override behavior
Explanation
A child class extends a parent class, gaining its members while being able to add new ones or override existing ones.
12
What does "this" (or "self") typically refer to inside an instance method?
Correct Answer
The current object instance on which the method was called
Explanation
"this" or "self" is a reference to the specific object the method is operating on, allowing access to its attributes.
13
What is "method overriding"?
Correct Answer
A subclass providing its own implementation of a method already defined in its parent class
Explanation
Overriding lets a subclass replace the inherited behavior of a method with its own version, supporting runtime polymorphism.
14
What is "method overloading"?
Correct Answer
Defining multiple methods with the same name but different parameter lists within the same class
Explanation
Overloading allows a class to have several methods with the same name distinguished by their parameters (not supported in all languages, e.g. Python).
15
What access modifier typically makes a class member accessible only within its own class?
Correct Answer
Private
Explanation
Private members can only be accessed from within the class that declares them, supporting encapsulation.
16
What access modifier typically allows a class member to be accessed from any code that has access to the object?
Correct Answer
Public
Explanation
Public members form part of a class's external interface and can be accessed from outside the class.
17
What access modifier typically allows access from the declaring class and its subclasses, but not from unrelated classes?
Correct Answer
Protected
Explanation
Protected members are visible to the defining class and its subclasses, balancing encapsulation with reuse via inheritance.
18
What is an "interface" in OOP?
Correct Answer
A contract that specifies methods a class must implement, without providing their implementation
Explanation
An interface declares method signatures that implementing classes must provide, enabling polymorphism without shared inheritance.
19
What is an "abstract class"?
Correct Answer
A class that cannot be instantiated directly and may contain both implemented and unimplemented methods
Explanation
Abstract classes provide a partial implementation and define a common template, leaving some methods for subclasses to implement.
20
What is "composition" in OOP?
Correct Answer
Building complex objects by combining simpler objects as parts (a "has-a" relationship)
Explanation
Composition models a "has-a" relationship, where one object contains references to other objects to delegate behavior to them.
21
What is a "static" method or field?
Correct Answer
One that belongs to the class itself rather than to any individual instance
Explanation
Static members are shared across all instances and can be accessed via the class name, without needing an object.
22
What is a "destructor"?
Correct Answer
A special method invoked when an object is about to be destroyed, used for cleanup
Explanation
Destructors free resources (like file handles or connections) held by an object before it is removed from memory.
23
What term describes the real-world relationship "a Car has an Engine"?
Correct Answer
Aggregation/Composition
Explanation
"Has-a" relationships are modeled using composition or aggregation, where one class contains an instance of another.
24
What term describes the relationship "a Dog is an Animal"?
Correct Answer
Inheritance ("is-a" relationship)
Explanation
"Is-a" relationships are modeled with inheritance, where a subclass is a more specific kind of its parent class.
25
What is the purpose of a "getter" method?
Correct Answer
To provide controlled read access to a private attribute
Explanation
Getters expose a private field's value in a controlled way, often allowing validation or computed logic.
26
What is the purpose of a "setter" method?
Correct Answer
To provide controlled write access to a private attribute, often including validation
Explanation
Setters allow an object's state to be modified while enforcing rules, such as rejecting invalid values.
27
In most class-based OOP languages, what keyword is commonly used to create a new object instance?
Correct Answer
new
Explanation
The "new" keyword allocates memory for an object and calls its constructor to initialize it.
28
What does it mean for a method to be "final" (or non-overridable)?
Correct Answer
It cannot be overridden by a subclass
Explanation
Marking a method final prevents subclasses from changing its behavior, useful when the implementation must not vary.
29
What is a "constant" in the context of a class?
Correct Answer
A field whose value is fixed and cannot be reassigned after initialization
Explanation
Constants represent fixed values, such as mathematical constants or configuration values, that should never change.
30
What is the main benefit of encapsulation?
Correct Answer
It protects an object's internal state from invalid external changes and reduces coupling
Explanation
By hiding internal details, encapsulation ensures objects can only be modified through valid, controlled operations.
31
What is a "namespace" (or "package" / "module") used for in OOP languages?
Correct Answer
To organize classes into logical groups and avoid naming conflicts
Explanation
Namespaces group related classes and prevent collisions between identically named classes from different libraries.
32
What is "dot notation" commonly used for in OOP?
Correct Answer
Accessing an object's attributes and methods, e.g. object.attribute or object.method()
Explanation
Dot notation lets you reach into an object to read attributes or invoke its methods.
33
What is the term for creating a new object from a class called?
Correct Answer
Instantiation
Explanation
Instantiation is the process of creating a specific object (instance) from a class definition.
34
Which of these is an example of a real-world analogy for a class and its objects?
Correct Answer
A cookie cutter (class) and the cookies it makes (objects)
Explanation
The cookie cutter is the template (class); each cookie made from it is a separate object with the same shape but possibly different toppings (attribute values).
35
Why might a class have multiple constructors with different parameters?
Correct Answer
To allow objects to be created in different ways depending on the information available
Explanation
Multiple constructors (an application of overloading) give callers flexibility, e.g. creating an object with default values or with specific ones.
36
What does it mean for a class to "implement" an interface?
Correct Answer
The class provides concrete implementations for all the methods declared by the interface
Explanation
Implementing an interface is a commitment by the class to provide working code for every method the interface declares.
37
What is a "property" (or "field") of a class?
Correct Answer
A piece of data associated with a class or its instances
Explanation
Properties (fields/attributes) represent the state stored by an object, such as a Person's name or age.
38
In OOP, what does "is-a" describe, as opposed to "has-a"?
Correct Answer
An inheritance relationship, where one class is a specialized type of another
Explanation
"Is-a" signals inheritance (e.g. a Square is a Shape), while "has-a" signals composition (e.g. a Car has an Engine).
39
What happens if a subclass does not override a method from its parent class?
Correct Answer
The subclass inherits and uses the parent's implementation of that method
Explanation
Unless overridden, a subclass simply uses the inherited version of a method as-is.
40
What is a key advantage of using OOP for large software systems?
Correct Answer
It promotes modularity, reusability, and easier maintenance through organized, encapsulated units
Explanation
OOP's structure of classes and objects helps organize complex systems into manageable, reusable, and maintainable pieces.
1
What is the difference between "method overloading" and "method overriding"?
Correct Answer
Overloading is multiple methods with the same name but different signatures in one class; overriding is a subclass redefining a parent method with the same signature
Explanation
Overloading is resolved at compile time based on argument types/count; overriding is resolved at runtime based on the actual object type (dynamic dispatch).
2
What is "dynamic (runtime) polymorphism" typically implemented through?
Correct Answer
Method overriding combined with a reference of a base type pointing to a derived object
Explanation
When a base-type reference calls an overridden method, the actual method executed is determined by the object's real (derived) type at runtime.
3
Why might a class be designed to favor composition over inheritance?
Correct Answer
Composition offers more flexibility, avoids tight coupling to a rigid hierarchy, and allows behavior to change at runtime
Explanation
"Favor composition over inheritance" is a design principle because deep inheritance hierarchies can become fragile and hard to change, whereas composed objects can be swapped independently.
4
What problem does the "diamond problem" refer to?
Correct Answer
Ambiguity that arises when a class inherits from two classes that both inherit from a common ancestor with conflicting members
Explanation
The diamond problem occurs in multiple inheritance when it is unclear which parent's version of an inherited member should be used; some languages avoid this by disallowing multiple class inheritance.
5
What is an "abstract method"?
Correct Answer
A method declared without an implementation, which must be implemented by concrete subclasses
Explanation
Abstract methods define a required behavior signature, leaving the actual implementation to subclasses, enforcing a contract.
6
What is the purpose of the "Liskov Substitution Principle" (the L in SOLID)?
Correct Answer
Subclasses should be replaceable for their base classes without altering correct program behavior
Explanation
LSP states that code using a base class reference should work correctly even when given an instance of any subclass, preserving expected behavior and invariants.
7
What does the "Single Responsibility Principle" (the S in SOLID) state?
Correct Answer
A class should have only one reason to change, i.e. one well-defined responsibility
Explanation
Keeping a class focused on a single responsibility makes it easier to understand, test, and modify without unintended side effects elsewhere.
8
What does the "Open/Closed Principle" (the O in SOLID) state?
Correct Answer
Software entities should be open for extension but closed for modification
Explanation
New behavior should be added by extending existing code (e.g. via subclassing or interfaces) rather than altering tested, working code.
9
What does the "Interface Segregation Principle" (the I in SOLID) state?
Correct Answer
Clients should not be forced to depend on methods they do not use; prefer many small, specific interfaces over one large one
Explanation
Splitting large "fat" interfaces into smaller, role-specific ones avoids forcing implementing classes to define methods irrelevant to them.
10
What does the "Dependency Inversion Principle" (the D in SOLID) state?
Correct Answer
High-level modules should not depend on low-level modules directly; both should depend on abstractions
Explanation
By depending on abstractions (interfaces) rather than concrete implementations, modules become decoupled and easier to swap or test.
11
What is a "design pattern"?
Correct Answer
A general, reusable solution to a commonly occurring problem within a given context in software design
Explanation
Design patterns are proven templates for structuring solutions to recurring design problems, not finished code that can be copy-pasted directly.
12
Which design pattern ensures a class has only one instance and provides a global access point to it?
Correct Answer
Singleton
Explanation
The Singleton pattern restricts instantiation of a class to a single object, often used for shared resources like configuration managers.
13
Which design pattern defines a one-to-many dependency so that when one object changes state, all its dependents are notified?
Correct Answer
Observer
Explanation
The Observer pattern lets "subscriber" objects react automatically to state changes in a "subject" object, common in event-driven systems.
14
Which design pattern provides an interface for creating objects without specifying their concrete classes?
Correct Answer
Factory Method
Explanation
The Factory Method pattern delegates object creation to subclasses or factory methods, decoupling client code from concrete class names.
15
What is the purpose of the "Strategy" design pattern?
Correct Answer
To encapsulate interchangeable algorithms or behaviors and select one at runtime
Explanation
Strategy defines a family of algorithms behind a common interface, letting the client choose or swap implementations without changing its own code.
16
What is the purpose of the "Decorator" design pattern?
Correct Answer
To attach additional responsibilities to an object dynamically without altering its class
Explanation
Decorators wrap an object to add new behavior (e.g. logging, caching) while preserving the same interface, allowing flexible feature combinations.
17
What is the purpose of the "Adapter" design pattern?
Correct Answer
To allow incompatible interfaces to work together by wrapping one in an interface the client expects
Explanation
An adapter translates calls from one interface into calls compatible with another, often used to integrate legacy or third-party code.
18
What does "duck typing" mean (notably in languages like Python or Ruby)?
Correct Answer
An object's suitability is determined by the presence of certain methods/properties, rather than its actual type or class
Explanation
"If it walks like a duck and quacks like a duck, it's a duck" — duck typing focuses on behavior (methods present) rather than explicit type declarations.
19
What is a "mixin"?
Correct Answer
A class designed to provide methods to other classes via inclusion/composition rather than being instantiated on its own
Explanation
Mixins let classes share reusable functionality across unrelated class hierarchies without using traditional single inheritance.
20
In OOP, what is a "shallow copy" of an object?
Correct Answer
A copy where the top-level object is duplicated, but nested objects are shared by reference with the original
Explanation
Shallow copies create a new top-level object but reuse references to nested objects, so changes to nested data affect both copies.
21
In OOP, what is a "deep copy" of an object?
Correct Answer
A copy that recursively duplicates the object and all objects it references, producing a fully independent clone
Explanation
Deep copies ensure the cloned object and its nested data are completely independent from the original, so modifying one does not affect the other.
22
What is "operator overloading"?
Correct Answer
Defining custom behavior for operators (like +, -, ==) when applied to objects of a user-defined class
Explanation
Operator overloading lets classes define what operators mean for their instances, e.g. making "+" concatenate or combine two custom objects.
23
Why are immutable objects (objects whose state cannot change after creation) often preferred in certain designs?
Correct Answer
They are inherently thread-safe and easier to reason about since their state never changes unexpectedly
Explanation
Because immutable objects can't be modified after construction, they avoid issues from shared mutable state, especially in concurrent code.
24
What is the purpose of an abstract class's constructor if the class cannot be instantiated directly?
Correct Answer
It can be called by subclass constructors (via super/parent calls) to initialize shared state
Explanation
Subclasses commonly call the abstract parent's constructor to set up inherited fields before adding their own initialization.
25
What does it mean for a class to have "high cohesion"?
Correct Answer
Its members and methods are closely related and focused on a single, well-defined purpose
Explanation
High cohesion means everything in the class works together toward one purpose, making the class easier to understand and maintain.
26
What does "loose coupling" between classes mean, and why is it desirable?
Correct Answer
Classes have minimal dependencies on each other's internal details, making changes in one less likely to break others
Explanation
Loosely coupled classes interact through stable interfaces, so internal changes in one class are less likely to ripple through the system.
27
What is a "constructor chaining" (or calling another constructor from within a constructor, e.g. via super() or this())?
Correct Answer
Calling one constructor from another (in the same or parent class) to avoid duplicating initialization logic
Explanation
Constructor chaining lets one constructor reuse another's initialization logic, reducing duplication when multiple constructors exist.
28
What is the difference between an interface and an abstract class (in languages that support both)?
Correct Answer
An interface typically defines only method signatures (a pure contract), while an abstract class can provide partial implementation and state
Explanation
Interfaces declare a contract without shared implementation (in classic form), while abstract classes can mix abstract and concrete methods plus shared fields.
29
What is "multiple inheritance"?
Correct Answer
A class inheriting from more than one parent class at once
Explanation
Multiple inheritance lets a class derive from several base classes; some languages (e.g. Java, C#) disallow it for classes to avoid ambiguity, often offering interfaces instead.
30
What is a "virtual method" (in languages like C++ or C#)?
Correct Answer
A method that can be overridden in a derived class and is resolved via dynamic dispatch at runtime
Explanation
Marking a method virtual signals that derived classes may override it, and calls through a base reference will use the derived implementation.
31
What is the benefit of programming "to an interface" rather than a concrete implementation?
Correct Answer
It decouples client code from specific implementations, allowing different implementations to be swapped in without changing client code
Explanation
Depending on an interface means the underlying implementation can change or be replaced (e.g. for testing with mocks) without affecting code that uses it.
32
What is a "factory" in the context of object creation patterns?
Correct Answer
An object or method whose responsibility is to create other objects, often hiding the instantiation logic
Explanation
Factories centralize and encapsulate object creation logic, useful when creation involves complex setup or choosing between several related classes.
33
What does the term "god object" (or "god class") describe as an anti-pattern?
Correct Answer
A class that knows or does too much, violating single responsibility and becoming hard to maintain
Explanation
A "god object" centralizes too much logic and state, making the system tightly coupled to it and difficult to test or extend.
34
What does it mean to "compose" behaviors via dependency injection?
Correct Answer
Supplying a class's dependencies (often as interfaces) from outside, rather than having it create them itself
Explanation
Dependency injection passes required collaborators into a class (e.g. via constructor), improving testability and reducing tight coupling to concrete implementations.
35
In a class hierarchy, what is "covariant return type"?
Correct Answer
An overriding method returning a more specific (derived) type than the type returned by the overridden method
Explanation
Covariant return types allow an overriding method to narrow the return type to a subtype, which is type-safe since the subtype satisfies the original contract.
36
What is the main risk of using "protected" fields extensively in a class hierarchy?
Correct Answer
It can tightly couple subclasses to the parent's internal implementation, making future changes to the parent risky
Explanation
Exposing internals to subclasses via protected access breaks encapsulation between parent and child, so changing the parent's internals can silently break subclasses.
37
What is "encapsulation" most directly in tension with, if overused without any public interface?
Correct Answer
Usability — an object with no way to interact with its data becomes useless to other code
Explanation
If everything is private with no accessors or methods, other code cannot interact with the object meaningfully, so a balance between hiding and exposing is needed.
38
What is a "value object" in OOP design?
Correct Answer
An object whose equality is based on its attribute values rather than its identity, often designed to be immutable
Explanation
Value objects (e.g. Money, Point, DateRange) are compared by their data rather than reference identity, and immutability avoids accidental shared-state bugs.
39
When designing class hierarchies, why is "is-a" sometimes a misleading guide for inheritance (e.g. "a Square is-a Rectangle")?
Correct Answer
Because subclassing must always preserve behavioral expectations (LSP); a Square subclassing Rectangle can violate invariants if width/height are independently settable
Explanation
The classic Square/Rectangle example shows that a conceptual "is-a" relationship can break the Liskov Substitution Principle if the subclass cannot honor all behaviors expected of the parent.
40
What is a common reason to use the "Template Method" design pattern?
Correct Answer
To define the skeleton of an algorithm in a base class while letting subclasses override specific steps
Explanation
Template Method fixes the overall structure of an algorithm in the parent while deferring certain customizable steps to subclasses via overridable methods.
1
What is "double dispatch" and why is it relevant to polymorphism?
Correct Answer
A mechanism where the method executed depends on the runtime types of two objects involved (e.g. the receiver and an argument), beyond simple single dispatch
Explanation
Most OOP languages support single dispatch (based on the receiver's type only); double dispatch resolves behavior based on two objects' types, often implemented via the Visitor pattern.
2
How does the "Visitor" design pattern relate to double dispatch?
Correct Answer
It simulates double dispatch by having elements accept a visitor, which then calls a type-specific visit method on itself
Explanation
The Visitor pattern lets new operations be added to a class hierarchy without modifying the classes, by combining the element's accept() call with the visitor's overloaded visit() methods, achieving double dispatch.
3
What is "object slicing" in languages like C++?
Correct Answer
Losing the derived-class-specific members when a derived object is assigned (by value) to a base-class variable
Explanation
When a derived object is copied into a base-type variable by value, only the base portion is copied, "slicing off" the derived part — a pitfall avoided by using references or pointers.
4
In the context of the SOLID principles, what is a "fragile base class" problem?
Correct Answer
A scenario where seemingly safe modifications to a base class break the behavior of derived classes that depend on its implementation details
Explanation
Subclasses may implicitly rely on a base class's internal behavior (not just its documented contract), so changes to the base — even bug fixes — can silently break subclasses.
5
What is "mixin composition" used to solve compared to traditional multiple inheritance?
Correct Answer
It provides a way to reuse behavior across unrelated classes while avoiding the ambiguity of the diamond problem, often by linearizing the inclusion order
Explanation
Languages like Ruby use a method resolution order (MRO) to linearize mixins, so each included module has a well-defined place in the lookup chain, avoiding diamond ambiguity.
6
What is the difference between "structural subtyping" and "nominal subtyping"?
Correct Answer
Structural subtyping determines compatibility based on the shape (members) of a type, while nominal subtyping requires an explicit declared relationship (e.g. extends/implements)
Explanation
Languages like Go and TypeScript use structural typing (a type satisfies an interface if it has matching members), while Java and C# use nominal typing (a class must explicitly declare implements).
7
Why can excessive use of inheritance lead to violation of encapsulation, sometimes summarized as "inheritance breaks encapsulation"?
Correct Answer
Because subclasses can depend on and be affected by the implementation details of their superclasses, not just their public contracts
Explanation
A subclass that overrides methods may unintentionally interact poorly with internal calls the superclass makes to itself, coupling the subclass to implementation details rather than just the interface.
8
What is "covariance" and "contravariance" as applied to method parameters and return types in OOP type systems?
Correct Answer
Covariance allows a subtype in place of return types (narrower), and contravariance allows a supertype in place of parameter types (wider), while preserving type safety for overriding
Explanation
For an override to be safe, return types may be narrowed (covariant) while parameter types may be widened (contravariant), matching the Liskov Substitution Principle's requirements.
9
What is the purpose of the "Null Object" pattern?
Correct Answer
To provide an object with neutral ("do nothing") behavior in place of a null reference, avoiding null checks throughout the code
Explanation
A Null Object implements the expected interface with no-op behavior, so client code can call methods on it safely without special-casing null, reducing defensive checks.
10
In languages supporting "generics" or "templates", how does this relate to OOP polymorphism?
Correct Answer
Generics provide "parametric polymorphism", allowing classes and methods to operate on any type while preserving type safety, distinct from subtype polymorphism via inheritance
Explanation
Parametric polymorphism (generics/templates) lets code be written once and reused for many types with compile-time type checking, complementing (not replacing) subtype/inheritance-based polymorphism.
11
What does "favor delegation over inheritance" mean as a design heuristic?
Correct Answer
A class should hold a reference to another object and forward (delegate) certain calls to it, rather than inheriting that object's implementation
Explanation
Delegation achieves code reuse similarly to inheritance but with looser coupling, since the delegating object can change its delegate at runtime and is not bound to the delegate's full interface or hierarchy.
12
How do "abstract classes" and "interfaces with default methods" (e.g. Java 8+ default methods) compare in terms of evolving APIs?
Correct Answer
Default methods let interfaces add new methods with a default implementation without breaking existing implementing classes, narrowing (but not eliminating) the gap with abstract classes
Explanation
Before default methods, adding a new method to an interface broke all implementers; default methods allow backward-compatible interface evolution, though abstract classes still allow shared state (fields) which interfaces traditionally cannot.
13
What subtle issue can arise from calling an overridable (virtual) method from within a constructor?
Correct Answer
The overridden version in a subclass may execute before the subclass's own fields have been initialized, leading to unexpected state
Explanation
During base class construction, if a virtual method is called and overridden by a subclass, the subclass override may run against partially-initialized subclass state, a well-known pitfall in many OOP languages.
14
What is "interface pollution" and how do SOLID principles address it?
Correct Answer
When an interface accumulates too many unrelated methods, forcing implementers to provide irrelevant or stub implementations; the Interface Segregation Principle addresses this by splitting into focused interfaces
Explanation
Bloated interfaces force unrelated implementers to deal with methods they don't need, often resulting in empty or exception-throwing stub methods — ISP recommends smaller, role-based interfaces instead.
15
How does the "Open/Closed Principle" relate to the Strategy and Template Method patterns?
Correct Answer
Both patterns allow new behaviors to be added (via new strategy classes or overridden template steps) without modifying existing, tested code
Explanation
Both patterns provide extension points (a new Strategy implementation, or an overridden template step) so that adding new behavior does not require modifying the existing class that uses them — the essence of OCP.
16
In a deep inheritance hierarchy, what is the "yo-yo problem"?
Correct Answer
The need to repeatedly jump up and down the class hierarchy to understand which method implementation actually executes for a given call
Explanation
Deep hierarchies with many overridden methods can force developers to trace execution back and forth across many classes ("yo-yo") to follow a single method call's actual behavior.
17
What does it mean for a method to be "idempotent" in the context of object state mutation, and why might this matter for OOP API design?
Correct Answer
Calling it multiple times has the same effect as calling it once, which makes APIs more predictable and safer to retry, e.g. in distributed systems
Explanation
Idempotent methods (e.g. "setStatus('done')" called twice) leave the object in the same state regardless of repeated calls, which simplifies error handling and retries in larger systems.
18
How can "encapsulation" and "testability" sometimes conflict, and what is a common resolution?
Correct Answer
Strict encapsulation can hide state needed for verifying behavior in tests; a common resolution is to test via the public interface and use dependency injection to substitute collaborators rather than exposing internals
Explanation
Rather than breaking encapsulation by exposing private state, well-designed classes can be tested through their public behavior, with dependencies injected so test doubles can observe interactions indirectly.
19
What is the relationship between the "Composite" design pattern and polymorphism?
Correct Answer
Composite lets individual objects and compositions of objects be treated uniformly through a shared interface, relying on polymorphism so client code does not need to distinguish leaves from containers
Explanation
In Composite, both "leaf" and "composite" (container) nodes implement a common component interface, so client code can call the same methods on either without type checks — a direct application of polymorphism.
20
Why might overusing "static" methods and classes undermine the benefits of OOP design?
Correct Answer
Static methods cannot be overridden or polymorphically dispatched, and heavy reliance on them can create hidden global state and make unit testing (mocking) more difficult
Explanation
Because static methods are bound at compile time and not part of an object's polymorphic interface, overusing them reduces flexibility, increases coupling to specific implementations, and complicates substituting test doubles.