1. What does Object Oriented Programming mainly focus on?
Difficulty: EasyType: MCQTopic: OOP Basics
- Using functions to perform tasks
- Representing real-world entities using objects and classes
- Writing code without any structure
- Executing commands line by line
Object Oriented Programming models real-world entities as objects that contain both data and behavior. This makes programs modular, reusable, and easier to maintain compared to procedural approaches.
Correct Answer: Representing real-world entities using objects and classes
2. What is the relationship between a class and an object?
Difficulty: EasyType: MCQTopic: Classes Objects
- A class is an instance of an object
- An object is an instance of a class
- They are the same thing
- A class cannot create objects
A class acts as a blueprint that defines structure and behavior, while an object is a concrete instance created from that blueprint. You can create multiple objects from a single class.
Correct Answer: An object is an instance of a class
Example Code
class Car { }
Car c1 = new Car();3. What is encapsulation in OOP?
Difficulty: MediumType: MCQTopic: Encapsulation
- Combining code and data into a single unit
- Dividing a program into multiple functions
- Writing all variables as global
- Using many classes in one program
Encapsulation binds data and methods together inside a class, preventing direct external access. It improves data security and modularity by using access modifiers like private and public.
Correct Answer: Combining code and data into a single unit
Example Code
class Account {
private double balance;
public void deposit(double amt){ balance += amt; }
}4. Explain abstraction and how it helps in reducing program complexity.
Difficulty: MediumType: SubjectiveTopic: Abstraction
Abstraction means showing only essential features of an object while hiding the implementation details. It lets developers work with higher-level concepts without worrying about the inner code. For instance, a 'Car' class exposes methods like start() or brake(), but hides how the engine works. Abstraction reduces complexity, increases focus, and simplifies system design.
5. Which OOP principle allows a class to use properties and behavior of another class?
Difficulty: MediumType: MCQTopic: Inheritance
- Polymorphism
- Encapsulation
- Abstraction
- Inheritance
Inheritance allows a class (child) to reuse and extend the functionality of another class (parent). It promotes code reuse and hierarchical classification.
Correct Answer: Inheritance
Example Code
class Animal { void eat(){} }
class Dog extends Animal { }6. Polymorphism in OOP allows what kind of behavior?
Difficulty: MediumType: MCQTopic: Polymorphism
- Objects behaving differently based on data type or context
- Combining data and code
- Sharing the same memory between objects
- Restricting object creation
Polymorphism means 'many forms'. It allows the same method name or operator to behave differently depending on the object or context, such as method overloading (compile time) or overriding (runtime).
Correct Answer: Objects behaving differently based on data type or context
Example Code
class Shape { void draw(){} }
class Circle extends Shape { void draw(){} }7. What is method overloading?
Difficulty: MediumType: MCQTopic: Method Overload
- Defining two methods with the same name but different parameters
- Redefining a parent class method in a child class
- Changing a variable type at runtime
- Creating multiple classes with the same name
Method overloading allows a class to have multiple methods with the same name but different parameter lists. It improves code readability and flexibility by handling different input types or counts.
Correct Answer: Defining two methods with the same name but different parameters
Example Code
int add(int a,int b){return a+b;}
double add(double a,double b){return a+b;}8. Which concept allows a subclass to redefine a method already defined in its superclass?
Difficulty: MediumType: MCQTopic: Method Override
- Overriding
- Overloading
- Encapsulation
- Composition
Method overriding lets a subclass modify or extend the behavior of a method inherited from the superclass. It supports runtime polymorphism. The method signatures must match exactly.
Correct Answer: Overriding
Example Code
class Parent { void show(){} }
class Child extends Parent { void show(){ System.out.println("Child"); } }9. Describe the lifecycle of an object in OOP.
Difficulty: MediumType: SubjectiveTopic: Object Lifecycle
An object’s lifecycle starts when it is instantiated using a constructor. It lives in memory, interacting through methods and attributes. When it is no longer referenced, it becomes eligible for destruction or garbage collection. Understanding this helps manage memory efficiently and avoid resource leaks.
10. Which access modifier makes a member accessible only within its own class?
Difficulty: MediumType: MCQTopic: Access Control
- public
- protected
- private
- default
The private modifier restricts access to members so they can be used only within the same class. It enforces encapsulation by preventing outside modification of internal data.
Correct Answer: private
Example Code
class Person { private int age; }11. Explain the concept of composition and how it differs from inheritance.
Difficulty: MediumType: SubjectiveTopic: Composition
Composition means building complex objects by combining simpler ones. For example, a 'Car' class can have an 'Engine' object inside it. It represents a 'has-a' relationship, while inheritance represents an 'is-a' relationship. Composition promotes flexibility since components can be changed without affecting the parent class hierarchy.
12. Give a real-world example illustrating all four major OOP principles together.
Difficulty: MediumType: SubjectiveTopic: OOP Basics
Consider a 'Banking System'. The 'Account' class hides sensitive data through encapsulation. Different account types like 'Savings' and 'Current' inherit from 'Account'. Common methods like calculateInterest() are overridden (polymorphism). The user interacts through high-level operations such as deposit() or withdraw(), without seeing the internal logic—this is abstraction. Combining these demonstrates how OOP models real-world systems naturally.
13. Which of the following is NOT a benefit of OOP?
Difficulty: EasyType: MCQTopic: OOP Basics
- Code reusability
- Improved maintainability
- Higher security through encapsulation
- Increased code redundancy
OOP aims to reduce redundancy, not increase it. Its modular design improves maintainability, reusability, and security by organizing code around real-world entities.
Correct Answer: Increased code redundancy
14. What is a class in object-oriented programming?
Difficulty: EasyType: MCQTopic: Classes Objects
- A single variable
- A blueprint or template for creating objects
- A function that returns an object
- An object instance already created
A class defines the attributes (data) and behaviors (methods) that its object instances will have. Think of it like a blueprint for constructing many similar objects.
Correct Answer: A blueprint or template for creating objects
15. Which statement correctly creates an object from class Car in Java?
Difficulty: EasyType: MCQTopic: Classes Objects
- Car car = new Car();
- Car car = Car();
- new Car car;
- Car car = Car.new();
In Java you use the new keyword with a constructor call to instantiate an object: new Car(). Then you can assign it to a reference of type Car.
Correct Answer: Car car = new Car();
16. What does a default constructor refer to?
Difficulty: MediumType: MCQTopic: Constructors
- A constructor with no parameters defined by the programmer
- Automatically provided constructor with no parameters if none is defined
- A constructor that always takes one argument
- A special constructor that can't be overridden
If you don’t define any constructor in many languages (for example Java or C++), the compiler supplies a default no-argument constructor. It allows object creation without supplying parameters.
Correct Answer: Automatically provided constructor with no parameters if none is defined
17. Which constructor takes arguments to initialize object at creation time?
Difficulty: MediumType: MCQTopic: Constructors
- Static constructor
- Copy constructor
- Parameterized constructor
- Destructor
A parameterized constructor allows passing values at the time of object creation, so the object can be initialized with different states immediately.
Correct Answer: Parameterized constructor
18. What is a copy constructor used for in C++?
Difficulty: HardType: MCQTopic: Object Copy
- Destructing an object automatically
- Creating a new object as a copy of an existing object
- Initializing static variables only
- Allocating global resources
A copy constructor in C++ constructs a new object by copying values from an existing object. It’s used for object duplication and deep or shallow copy semantics.
Correct Answer: Creating a new object as a copy of an existing object
19. What is constructor chaining?
Difficulty: MediumType: MCQTopic: Constructors
- Calling one constructor from another within the same class
- Creating multiple objects in one statement
- Overriding constructor in subclass
- Calling destructor from constructor
Constructor chaining means one constructor calls another in the same class (or base class) to reuse initialization logic. It helps avoid duplication and maintain consistent object setup.
Correct Answer: Calling one constructor from another within the same class
20. Which is true of static members versus instance members in a class?
Difficulty: MediumType: MCQTopic: Classes Objects
- Static members are tied to the class; instance members are tied to objects
- Instance members are shared by all objects; static members are unique per object
- Static members cannot be accessed without creating object
- Instance members exist only once per program
Static members belong to the class itself and are shared across all objects; instance members are part of each object’s state and vary from object to object.
Correct Answer: Static members are tied to the class; instance members are tied to objects
21. What is the purpose of a destructor in C++?
Difficulty: HardType: MCQTopic: Object Lifecycle
- To create an object automatically
- To free resources when object lifetime ends
- To overload functions
- To implement polymorphism
A destructor is called automatically when an object goes out of scope or is delete-ed. It allows cleanup of memory, file handles, or other resources.
Correct Answer: To free resources when object lifetime ends
22. Which operator in Java checks whether two object references point to the exact same object?
Difficulty: EasyType: MCQTopic: Classes Objects
- equals()
- ==
- hashCode()
- compareTo()
In Java the == operator checks if two references refer to the same object in memory, not if they are logically equal. equals() checks content equality if overridden.
Correct Answer: ==
23. Explain how constructor visibility (public, private etc.) affects object creation.
Difficulty: MediumType: SubjectiveTopic: Constructors
Constructor visibility determines from where an object can be created. A public constructor allows object creation from anywhere; a private constructor prevents external code from using it (useful in singletons). Protected or package-private allows controlled access. In interviews you might discuss design patterns like Singleton where private constructors are essential.
24. Differentiate between default and parameterised constructors with examples.
Difficulty: MediumType: SubjectiveTopic: Constructors
A default constructor takes no arguments; it either is provided implicitly or defined explicitly. A parameterised constructor takes one or more parameters for initialization. Example in Java: class Person { Person() { } Person(String name) { this.name=name; } } The difference influences how objects are created and initialised.
25. Describe the lifecycle of an object from creation to destruction including constructors and destructors/garbage-collection.
Difficulty: HardType: SubjectiveTopic: Object Lifecycle
When code uses new to create an object memory is allocated, the constructor (default or parameterised) initialises the object, and the object is ready for use. Later when it is no longer referenced (in languages with GC) or delete-ed (in C++), destructor or GC finaliser runs to free resources. Understanding this helps you reason about memory management and resource leaks in interviews.
26. What is the difference between shallow copy and deep copy of objects? Give examples.
Difficulty: HardType: SubjectiveTopic: Object Copy
A shallow copy duplicates the object but shares references of internal mutable objects; modifications in one reflect in the other. A deep copy duplicates the object and its entire internal structure so changes in one don’t affect the other. In C++ copy constructor or clone methods handle copying; in Java you might implement Cloneable or use serialization. Explaining pitfalls and when each is needed shows depth.
27. Explain how constructor chaining works in class inheritance (base and derived classes).
Difficulty: MediumType: SubjectiveTopic: Constructors
In inheritance the derived class constructor implicitly or explicitly calls its base class constructor before executing its body. This ensures base class state is properly initialised. In Java you use super(); in C++ you can specify initialiser list. Constructor chaining avoids duplicate code and handles complex object initialisation reliably.
28. What is single inheritance in object-oriented programming?
Difficulty: EasyType: MCQTopic: Inheritance
- A class inherits from multiple base classes
- A class doesn’t inherit any behaviour
- A class inherits from exactly one base class
- A class inherits only static members
Single inheritance is when a class (often called the child or subclass) inherits attributes and methods from exactly one parent (base or superclass). It allows the subclass to reuse and extend functionality in a straightforward “is-a” relationship without the complexity of multiple base classes.
Correct Answer: A class inherits from exactly one base class
29. What is true about multiple inheritance (in languages that support it)?
Difficulty: MediumType: MCQTopic: Inheritance
- A class can inherit implementation from more than one base class
- A class can only inherit from one base class but implement many interfaces
- A class cannot override methods when using multiple inheritance
- Multiple inheritance and polymorphism are the same
Multiple inheritance allows a subclass to inherit from more than one base class. This can enable rich reuse but also introduces challenges like the diamond problem. Some languages avoid it by using interfaces instead of full class inheritance.
Correct Answer: A class can inherit implementation from more than one base class
30. In OOP, the relationship between a subclass and its superclass is often referred to as?
Difficulty: EasyType: MCQTopic: Inheritance
- Has-a relation
- Uses-a relation
- Is-a relation
- Part-of relation
Inheritance expresses an “is-a” relationship: the subclass *is a* more specialized version of its superclass. For example a Dog is a Mammal. Using correct relationship terminology helps in design and interview discussions.
Correct Answer: Is-a relation
31. What is method overriding in OOP?
Difficulty: MediumType: MCQTopic: Method Override
- Defining two methods with same name but different parameters in same class
- A subclass defining a method with same signature as its superclass to provide specific behaviour
- A class inheriting only fields and no methods
- A function that calls itself recursively
Method overriding occurs when a subclass provides its own implementation of a method defined in its superclass, using the same signature. This enables runtime polymorphism – the correct method executes based on the object’s actual type.
Correct Answer: A subclass defining a method with same signature as its superclass to provide specific behaviour
32. Which of the following is an example of compile-time polymorphism?
Difficulty: MediumType: MCQTopic: Polymorphism
- Method overriding
- Method overloading
- Dynamic binding
- Interface dispatch
Compile-time polymorphism (also called static binding) is achieved by method overloading – defining multiple methods with the same name but different parameter lists (or types). The compiler decides which method to call before runtime.
Correct Answer: Method overloading
33. Which of these describes runtime polymorphism?
Difficulty: MediumType: MCQTopic: Polymorphism
- Method overloading resolved at compile time
- Operator overloading at compile time
- Method overriding resolved at runtime via base-class reference
- Newing an object constantly
Runtime polymorphism (or dynamic binding) occurs when a base‐class reference points to a subclass object, and the subclass’s overridden method is invoked at runtime based on the actual object type.
Correct Answer: Method overriding resolved at runtime via base-class reference
34. Given ‘Animal a = new Dog();’ which concept is illustrated?
Difficulty: HardType: MCQTopic: Polymorphism
- Encapsulation
- Composition
- Polymorphism via base-type reference
- Aggregation
When a base class reference holds a subclass object (Animal a = new Dog()), it demonstrates polymorphism: the code can treat various subclasses uniformly while each subclass exhibits its own behavior when methods are called.
Correct Answer: Polymorphism via base-type reference
35. One benefit of inheritance is:
Difficulty: MediumType: MCQTopic: Inheritance
- Tight coupling between classes
- Code duplication
- Code reuse and easier maintenance
- Less flexibility in design
Inheritance allows new classes to reuse existing functionality from base classes, reducing duplication and making maintenance easier. This is a major reason why inheritance is widely used in OOP design.
Correct Answer: Code reuse and easier maintenance
36. What is the “diamond problem” in multiple inheritance?
Difficulty: HardType: MCQTopic: File IO
- Problem where base class destructor is not called
- Ambiguity when two base classes of a class share a common ancestor
- When subclass overloads methods with different return types
- When garbage-collection fails in multiple inheritance
The diamond problem arises in languages with multiple inheritance when a class inherits from two classes which both inherit from a common base class. This can lead to ambiguity about which base class’s implementation to use. Many languages avoid this with interfaces or virtual inheritance.
Correct Answer: Ambiguity when two base classes of a class share a common ancestor
37. Explain how inheritance and polymorphism work together in OOP.
Difficulty: MediumType: SubjectiveTopic: Inheritance
Inheritance allows a subclass to derive properties and behaviors from a superclass, creating a hierarchical relationship. Polymorphism lets code written for the superclass type work with subclass objects too. Together they enable flexibility: you define general behavior once in the superclass and let each subclass provide its own specific implementation, while using the same interface. For instance, you might have a base class `Vehicle` with a method `drive()`, and subclasses `Car`, `Bike`, `Truck` override `drive()` differently. With polymorphism you can write `Vehicle v = new Car(); v.drive();` and the correct method executes depending on the actual object type. This combination supports code reuse, extension and maintainability.
38. Describe the types of inheritance (single, multilevel, hierarchical, multiple, hybrid) and give examples.
Difficulty: MediumType: SubjectiveTopic: Inheritance
Inheritance can take many forms: *Single inheritance* where a class inherits from one base class; *Multilevel inheritance* where a class inherits from a class which itself inherits another; *Hierarchical inheritance* where multiple subclasses inherit from the same superclass; *Multiple inheritance* where a class inherits from more than one base class (allowed in some languages); and *Hybrid inheritance* which combines two or more of the above. For example, in Java you might have `class Dog extends Animal` (single), `class Puppy extends Dog extends Animal` (multilevel), `class Cat extends Animal` and `class Dog extends Animal` (hierarchical). Explaining language support and limitations—such as Java not supporting multiple inheritance of classes—shows strong interview readiness.
39. Differentiate method overloading from method overriding and discuss their use-cases.
Difficulty: HardType: SubjectiveTopic: Method Compare
Method overloading (compile-time polymorphism) and method overriding (runtime polymorphism) are often confused but serve different purposes. Overloading lets multiple methods in the same class share a name but differ in parameter lists—useful when you want to provide multiple ways to call a method (for example `print(int)` and `print(String)`). Overriding means a subclass provides its own version of a method defined in a superclass. Overriding is used when you want to alter or extend behavior in derived classes (for example `class Bird { fly() }` and `class Penguin extends Bird { fly() { throw new CannotFlyException(); } }`). Showing when and why to use each is key for interviews.
40. What are the benefits of polymorphism in software design?
Difficulty: MediumType: SubjectiveTopic: Polymorphism
Polymorphism enables flexibility and scalability in code by allowing objects of different types to be treated uniformly through a common interface. It supports extendability—new subclasses can be introduced without modifying existing code. It enhances maintainability by decoupling code from specific implementations, and encourages use of interchangeable components. Mentioning how polymorphism underpins design patterns and frameworks helps in interview discussions.
41. Why should you avoid improper inheritance and prefer composition in some cases? Provide reasons.
Difficulty: HardType: SubjectiveTopic: Inheritance
While inheritance offers reuse, it can also introduce tight coupling, fragility when base classes change, and violates encapsulation if subclass depends heavily on parent internals. Composition (‘has-a’ relationship) is often more flexible: you can change behaviour at run time by delegating to different components and avoid deep inheritance hierarchies. In interviews highlighting “favor composition over inheritance” demonstrates sound design sense.
42. What is encapsulation in object-oriented programming?
Difficulty: EasyType: MCQTopic: Encapsulation
- Hiding implementation details while exposing essential methods
- Classifying objects into categories
- Dividing a program into multiple threads
- Defining methods without parameters
Encapsulation is about bundling data and methods that operate on that data within a class and restricting direct access from outside. This protects internal state and promotes modular design.
Correct Answer: Hiding implementation details while exposing essential methods
43. What does abstraction focus on in OOP?
Difficulty: EasyType: MCQTopic: Abstraction
- Presenting only the relevant features of an entity and hiding the rest
- Allowing multiple classes to inherit from one class
- Overloading methods with many parameters
- Managing memory manually
Abstraction simplifies complex systems by providing a high-level interface and hiding lower-level implementation details. It helps designers focus on what an object does rather than how it does it.
Correct Answer: Presenting only the relevant features of an entity and hiding the rest
44. Which statement correctly distinguishes encapsulation from abstraction?
Difficulty: MediumType: MCQTopic: Abstraction
- Encapsulation shows what an object does; abstraction hides it
- Abstraction defines behavior; encapsulation hides data and implementation details
- Encapsulation is about inheritance; abstraction is about polymorphism
- They are exactly the same concept
Abstraction deals with exposing only essential features (the ‘what’), while encapsulation deals with hiding internal workings and grouping data and methods (the ‘how’) into a unit.
Correct Answer: Abstraction defines behavior; encapsulation hides data and implementation details
45. Which access modifier is most commonly used in encapsulation to hide a field from external access?
Difficulty: MediumType: MCQTopic: Access Control
- public
- private
- protected
- internal
Using the private modifier restricts a field or method to the defining class only. External classes must use public or protected methods (getters/setters) to interact, which enforces encapsulation.
Correct Answer: private
46. Using an interface to define common methods without implementation is an example of which OOP principle?
Difficulty: MediumType: MCQTopic: Abstract Types
- Encapsulation
- Abstraction
- Polymorphism
- Inheritance
An interface declares what methods a class must provide while hiding how they are implemented. This is a classic abstraction mechanism, focusing on behaviour rather than implementation.
Correct Answer: Abstraction
47. What is the main benefit of data hiding in encapsulation?
Difficulty: MediumType: MCQTopic: Encapsulation
- Faster execution
- Reduced memory usage
- Improved integrity and control over object state
- Simpler syntax
By hiding internal state and exposing controlled access, encapsulation ensures the object’s data remains valid, prevents unauthorized changes, and reduces bugs caused by misuse of internal fields.
Correct Answer: Improved integrity and control over object state
48. An abstract class cannot _____ in many OOP languages.
Difficulty: MediumType: MCQTopic: Abstract Types
- Define constructors
- Define methods with implementation
- Be instantiated directly
- Have subclass implementations
Abstract classes define interfaces or partial implementations. They require subclasses to provide concrete implementations and cannot be instantiated themselves, enforcing abstraction.
Correct Answer: Be instantiated directly
49. How does encapsulation support modularity in OOP?
Difficulty: MediumType: MCQTopic: Encapsulation
- By requiring all code to be in one class
- By separating internal implementation from interface and grouping related data and methods
- By avoiding use of classes
- By disallowing inheritance
Encapsulation helps build modules by isolating internals behind exposed interfaces. This improves maintainability, readability, and reduces coupling between modules.
Correct Answer: By separating internal implementation from interface and grouping related data and methods
50. What are the benefits of abstraction in object-oriented programming?
Difficulty: MediumType: SubjectiveTopic: Abstraction
Abstraction allows developers to focus on high-level design rather than implementation details. By exposing only relevant behaviour, it simplifies usage and hides complexity. This leads to improved maintainability, scalability and easier evolution of systems. For instance in a banking application you might expose operations like deposit() and withdraw(), while hiding how interest calculation or ledger maintenance is implemented.
51. Describe a use-case where encapsulation improves reliability and maintainability of code.
Difficulty: MediumType: SubjectiveTopic: Encapsulation
Consider a `BankAccount` class that keeps `balance` private and provides `deposit()` and `withdraw()` methods with internal checks (such as non-negative amounts and sufficient funds). This design hides the actual data, prevents external direct modification, enforces rules, and centralises validation logic. This encapsulation simplifies maintenance because changes to validation or logging only happen inside the class, not across the system.
52. Give an example code scenario illustrating both abstraction and encapsulation, and explain how they differ.
Difficulty: MediumType: SubjectiveTopic: Abstraction
Imagine a `Vehicle` interface with method `startEngine()`. The `Car` class implements `Vehicle` and hides its internal `engine` object and wiring inside `Car`. Users call `car.startEngine()` (abstraction) without knowing internal details. Internally, `engine` field is private and only exposed via methods (encapsulation). This shows abstraction at interface level and encapsulation at implementation level. Understanding this distinction is valuable for interviews.
53. What are the risks or drawbacks of improper encapsulation, and how can they be mitigated?
Difficulty: HardType: SubjectiveTopic: Encapsulation
If a class exposes its internal data directly (e.g., public fields), it opens the door to invalid state, brittle code and tight coupling. Changes to internal representation ripple across clients. To mitigate this, use access modifiers, provide well-defined interfaces, favour immutability, validate inputs in setters and keep internal logic behind private or protected methods. Designing classes with clear separation of concerns and using API contracts helps maintain encapsulation and system robustness.
54. What best describes an interface in object-oriented programming?
Difficulty: EasyType: MCQTopic: Abstract Types
- A blueprint for objects including state and behaviour
- A contract defining a set of methods without implementation
- A concrete class with full method implementations
- A special kind of object instance
An interface defines a set of methods (and sometimes constants) that implementing classes must provide. It describes what behaviour a class must offer without specifying how that behaviour is implemented. This enables loosely-coupled design and polymorphism.
Correct Answer: A contract defining a set of methods without implementation
55. Which statement correctly defines an abstract class?
Difficulty: EasyType: MCQTopic: Abstract Types
- A class that can be instantiated directly
- A class that cannot be instantiated and may contain both concrete and abstract methods
- A class with only static methods
- A class that does not allow inheritance
An abstract class serves as a base class that cannot be instantiated on its own. It may define some methods with implementation and leave others abstract for subclasses to override. This allows code reuse and enforcement of certain behaviours.
Correct Answer: A class that cannot be instantiated and may contain both concrete and abstract methods
56. In Java, how do you use an interface and how do you use an abstract class in declaration?
Difficulty: MediumType: MCQTopic: Abstract Types
- class MyClass implements MyAbstractClass; class MySub extends MyInterface
- class MyClass extends MyAbstractClass; class MySub implements MyInterface
- class MyClass extends MyInterface; class MySub implements MyAbstractClass
- You cannot use interfaces and abstract classes together
In Java, a class uses extends to inherit from a superclass (including an abstract class) and uses implements to implement an interface. This difference is key in object-oriented design.
Correct Answer: class MyClass extends MyAbstractClass; class MySub implements MyInterface
57. Which is true about interfaces and abstract classes regarding multiple inheritance in Java?
Difficulty: MediumType: MCQTopic: Inheritance
- A class can extend multiple abstract classes but implement only one interface
- A class can extend only one abstract class but may implement multiple interfaces
- A class may implement only one interface and extend only one abstract class
- Both abstract classes and interfaces support multiple inheritance equally
Java does not allow a class to extend more than one class, so you cannot have multiple class inheritance. However, a class can implement many interfaces, enabling multiple behaviour inheritance. This distinction is important for designing flexible APIs.
Correct Answer: A class can extend only one abstract class but may implement multiple interfaces
58. When would you prefer using an abstract class over an interface?
Difficulty: MediumType: MCQTopic: Abstract Types
- When you want only method signatures without implementation
- When you need to share code implementation among related classes plus define some contract
- When you need to restrict number of implementations to one class only
- When you never need to define any methods at all
An abstract class is useful when you have related classes that share common behaviour and some common code, as well as some methods you want subclasses to implement. Interfaces are about defining a contract, not sharing implementations.
Correct Answer: When you need to share code implementation among related classes plus define some contract
59. Which feature was added in Java 8 that changed how interfaces are used?
Difficulty: HardType: MCQTopic: Abstract Types
- Interfaces can now have state and constructors
- Interfaces can now have default and static methods with implementation
- Interfaces can now extend classes
- Interfaces can now be instantiated
From Java 8 onwards, interfaces may include default and static methods with implementations, allowing them to evolve over time without breaking existing implementations. This blurred the line between interfaces and abstract classes.
Correct Answer: Interfaces can now have default and static methods with implementation
60. Can an abstract class have a constructor and what is its purpose?
Difficulty: MediumType: MCQTopic: Abstract Types
- No, constructors are only for concrete classes
- Yes, and it is used to initialize fields when subclass objects are created
- Yes, but it can never be called
- Only if the abstract class has no abstract methods
Even though you cannot instantiate an abstract class directly, it can have a constructor which is called when a subclass is instantiated. This lets the abstract class initialize data common to all subclasses.
Correct Answer: Yes, and it is used to initialize fields when subclass objects are created
61. In Java, what are the properties of variables declared inside an interface by default?
Difficulty: MediumType: MCQTopic: Abstract Types
- public instance variables
- private final variables
- public static final constants
- protected non-static variables
In Java interfaces, variables are implicitly public, static and final (constants). They cannot be instance variables that vary per object.
Correct Answer: public static final constants
62. Explain how interfaces provide abstraction in OOP and give an example.
Difficulty: MediumType: SubjectiveTopic: Abstract Types
Interfaces provide abstraction by declaring methods without implementing them, allowing multiple classes to implement the same interface in their own way. This means you can write code that works with the interface type without knowing the concrete class implementation. For example, an interface `PaymentMethod` might define `processPayment(amount)`. Then classes `CreditCardPayment`, `PaypalPayment`, and `CryptoPayment` implement that interface. Your checkout module can depend on `PaymentMethod`, not concrete classes, enabling flexibility and easier substitution.
63. Compare abstract classes and interfaces, and describe when you would choose one over the other.
Difficulty: HardType: SubjectiveTopic: Abstract Types
Abstract classes and interfaces both support abstraction but differ in their use. An abstract class can include implemented methods, instance variables, constructors, and allows controlled inheritance; while an interface primarily defines a contract and supports multiple implementation. You would choose an abstract class when you have shared code among related classes and you want to enforce a base type. Use an interface when you want unrelated classes to share a capability or when you need multiple inheritance of behaviour. For example, you might have `Vehicle` as an abstract class with implementation for start() and stop(), and `Flyable` as an interface for anything that can fly. A `Car` class extends `Vehicle`, while `Helicopter` extends `Vehicle` and implements `Flyable`. This design shows when you pick each.
64. Given a scenario where you need to design a plugin architecture allowing many modules, some sharing common behaviour and others not, how would you use abstract classes and interfaces?
Difficulty: HardType: SubjectiveTopic: Abstract Types
In a plugin architecture you may define an interface `PluginModule` with methods like `initialize()` and `execute()`. This sets the contract for all modules. If some modules share common initialization code or data fields, you could provide an abstract class `BasePlugin` which implements `PluginModule` and offers default implementation of common logic. Then each concrete plugin class extends `BasePlugin`. This setup uses the interface for flexibility and abstract class for code reuse. Such hybrid designs are often expected in senior-level interviews.
65. What is a constructor in an object-oriented class?
Difficulty: EasyType: MCQTopic: Constructors
- A method automatically called when an object is created to initialize it
- A method called when an object is destroyed
- A global function outside any class
- A property that stores object state
A constructor is a special method of a class that is called when a new object is created. Its job is to initialize the new object’s state—setting up fields, allocating resources, or performing setup tasks so that the object is ready to use.
Correct Answer: A method automatically called when an object is created to initialize it
66. Which type of constructor takes no parameters and is provided automatically if no constructor is defined?
Difficulty: MediumType: MCQTopic: Constructors
- Copy constructor
- Default constructor
- Parameterized constructor
- Static constructor
A default constructor takes no arguments. Many OOP languages (for example Java or C++ when no constructor is defined) will automatically provide a default no-argument constructor to allow object creation without explicit parameters.
Correct Answer: Default constructor
67. What is the purpose of a parameterised constructor?
Difficulty: MediumType: MCQTopic: Constructors
- To create object without initialization
- To allow passing initialization values when creating an object
- To deallocate memory
- To enforce a class to have no objects
A parameterised constructor allows you to supply initial values for the object’s fields at the time of creation. This helps set up the object in the correct state from the outset and avoid separate setter calls afterwards.
Correct Answer: To allow passing initialization values when creating an object
68. In C++, what is a copy constructor used for?
Difficulty: HardType: MCQTopic: Object Copy
- Destroying an object
- Creating a new object from an existing object
- Allocating system memory outside class
- Preventing object creation
A copy constructor in C++ allows you to create a new object by copying the content of an existing object. It handles duplication of fields (shallow or deep copy). It is required when default copying would cause incorrect behaviour (e.g., shared pointers or dynamic memory).
Correct Answer: Creating a new object from an existing object
69. What is a destructor in object-oriented programming?
Difficulty: MediumType: MCQTopic: Object Lifecycle
- A method called before an object is destroyed to release resources
- A method that creates objects
- A method that copies objects
- A static method for utility tasks
A destructor is a special method that is invoked when an object’s lifetime ends. Its job is to clean up—free memory, close files, release locks, or deregister resources. In languages like C++ it is deterministic; in garbage-collected languages the timing may vary.
Correct Answer: A method called before an object is destroyed to release resources
70. Which of the following best describes the lifetime of an object?
Difficulty: MediumType: MCQTopic: Object Lifecycle
- From the end of its constructor to the next constructor call
- From object creation through initialization until destruction or garbage collection
- Only while a method is executing inside it
- Only during memory allocation
An object’s lifetime begins when it is created (constructor runs), then it exists in a usable state, and ends when it is destroyed or collected. During this time its state is consistent. Understanding object lifetime helps manage memory and resources correctly.
Correct Answer: From object creation through initialization until destruction or garbage collection
71. What is a memory leak in the context of objects?
Difficulty: HardType: MCQTopic: Memory Mgmt
- Freeing memory twice
- Failing to release memory or resources when objects are no longer needed
- Object having null reference
- Object being created inside loop
A memory leak occurs when objects or resources (memory, file handles) are not properly released after they are no longer used. Over time this degrades system performance and may cause failures. Proper design of constructors and destructors (or finalisers) is essential to avoid leaks.
Correct Answer: Failing to release memory or resources when objects are no longer needed
72. How does garbage collection differ from deterministic destruction in object-oriented languages?
Difficulty: MediumType: MCQTopic: Memory Mgmt
- It guarantees destruction at a specific time
- It frees resources immediately when object goes out of scope
- It defers destruction until the runtime decides, making cleanup non-deterministic
- It only works for stack-allocated objects
In garbage-collected languages (like Java, C#) objects are destroyed when the runtime’s GC deems them unreachable. This is non-deterministic compared to languages like C++ where destructors run immediately when scope ends or when delete is called. Understanding this helps interview candidates discuss resource management trade-offs.
Correct Answer: It defers destruction until the runtime decides, making cleanup non-deterministic
73. Explain constructor chaining and how it supports object initialization in class hierarchies.
Difficulty: MediumType: SubjectiveTopic: Constructors
Constructor chaining is when one constructor calls another constructor in the same class (or base class) to reuse initialization logic. In languages like Java you use `this(...)` to call another constructor in the same class, or `super(...)` to call the base class constructor. In C++ the base class constructor is called before the derived class constructor body executes. This ensures that shared initialization code is executed only once, and simplifies object construction across class hierarchies.
74. Describe shallow copy versus deep copy of objects and when each should be used.
Difficulty: HardType: SubjectiveTopic: Object Copy
A shallow copy duplicates the top-level object but shares references of nested or linked resources. This means that changes in one object’s nested resource affect the other. A deep copy duplicates both the object and all nested resources, so each object has its own independent state. Deep copy is needed when objects own resources (like dynamically allocated memory) that should not be shared. Many interviewers expect you to mention copy constructors, clone methods, and manage memory safely.
75. How are object cleanup tasks handled in Java and what are the limitations of finalisers?
Difficulty: MediumType: SubjectiveTopic: Memory Mgmt
In Java, there is no explicit destructor mechanism like in C++, but you can override `finalize()` or implement `AutoCloseable` and use try-with-resources for resource cleanup. However, `finalize()` is deprecated because its execution timing is unpredictable, it can delay resource release, and may introduce performance overhead. Therefore good design uses explicit close methods and avoids relying on GC for critical resource cleanup.
76. Explain the Rule of Three (and Rule of Five) in C++ and why it matters for memory management in classes.
Difficulty: HardType: SubjectiveTopic: Object Copy
In C++ the Rule of Three states that if you define a custom destructor, copy constructor or copy assignment operator then you should probably define all three to manage resources safely. With move semantics (C++11) this extends to the Rule of Five (add move constructor and move assignment). Following these rules prevents shallow copies, double deletion, and resource leaks. Interviewers who ask this expect you to recognise how constructors, destructors and assignment interplay in safe class design.
77. What is an exception in object-oriented programming?
Difficulty: EasyType: MCQTopic: Exceptions
- A syntax error at compile time
- An unexpected event during program execution that disrupts normal flow
- A regular return value from a method
- A method overloaded with many parameters
An exception is a runtime event that signals an error or unusual condition, such as dividing by zero or reading a missing file. Handling exceptions allows a program to respond gracefully rather than crashing.
Correct Answer: An unexpected event during program execution that disrupts normal flow
78. Which construct is used to handle exceptions in languages like Java and C#?
Difficulty: MediumType: MCQTopic: Exceptions
- if-else statement
- switch-case block
- try-catch block
- for loop
In Java and C#, developers wrap code that might throw an exception in a try block, and then catch specific exceptions in catch blocks. This structure ensures that exceptional conditions are caught and managed rather than causing program termination.
Correct Answer: try-catch block
79. What is the purpose of the finally clause in exception handling?
Difficulty: MediumType: MCQTopic: Exceptions
- To catch a second exception
- To always execute cleanup code whether exception occurs or not
- To start a new thread
- To define a new exception type
The finally block follows try and catch blocks and is guaranteed to execute whether an exception is thrown or handled. It is typically used to release resources like file handles or close database connections, ensuring no resource leak.
Correct Answer: To always execute cleanup code whether exception occurs or not
80. In Java, what distinguishes a checked exception from an unchecked exception?
Difficulty: HardType: MCQTopic: Exceptions
- Checked exceptions must be caught or declared in method signature, unchecked don’t
- Unchecked exceptions must be caught, checked don’t
- Checked exceptions occur only at compile time, unchecked at run time
- There is no difference
In Java checked exceptions inherit from Exception but not RuntimeException. The compiler forces you to either catch them or add throws clause. Unchecked exceptions (RuntimeException) are not required to be declared or caught, giving more flexibility but less compile-time safety.
Correct Answer: Checked exceptions must be caught or declared in method signature, unchecked don’t
81. Which class in Java is commonly used for reading text files line by line?
Difficulty: MediumType: MCQTopic: File IO
- FileWriter
- BufferedReader
- FileOutputStream
- Socket
BufferedReader wrapped around a FileReader allows efficient reading of text from a file line by line, reducing I/O overhead. It’s a standard pattern for file input operations in Java.
Correct Answer: BufferedReader
82. What is a resource leak in context of file I/O or other system resources?
Difficulty: MediumType: MCQTopic: Resource Mgmt
- Using too much memory intentionally
- Failing to close files or connections after use
- Reading from a file too slowly
- Writing large amounts of data
When system resources such as file handles, database connections or sockets are not properly closed, the program can exhaust these resources over time, leading to errors or degraded performance. Proper cleanup via finally blocks or try-with-resources is key.
Correct Answer: Failing to close files or connections after use
83. What is serialization in object-oriented programming?
Difficulty: HardType: MCQTopic: Serialization
- Converting an object into a format suitable for storage or transmission
- Running an object’s constructor twice
- Encrypting an object automatically
- Deleting an object from memory
Serialization converts an object’s state into a byte stream (or other format) so it can be written to disk or sent over a network. Later deserialization reconstructs the object. It is critical for persistence, caching and remote communication.
Correct Answer: Converting an object into a format suitable for storage or transmission
84. Which is considered a best practice in exception handling?
Difficulty: MediumType: MCQTopic: Exceptions
- Catching generic Exception everywhere
- Using exceptions for normal flow control
- Catching specific exception types and logging meaningful messages
- Suppressing all exceptions silently
Best practice is to catch only the exceptions you can handle, avoid swallowing errors silently, use meaningful logs, and rethrow or propagate when appropriate. This improves debuggability and system reliability.
Correct Answer: Catching specific exception types and logging meaningful messages
85. Explain the concept of try-with-resources (or similar constructs) and how it simplifies resource management.
Difficulty: MediumType: SubjectiveTopic: Resource Mgmt
In languages like Java you can use try-with-resources which automatically closes the resource at the end of the block, whether an exception was thrown or not. This reduces boilerplate finally code and prevents resource leaks. For example: `try (BufferedReader br = new BufferedReader(new FileReader(path))) { … }` ensures `br` is closed automatically. This pattern simplifies error-safe resource handling and is preferred in modern code.
86. Describe how and when you would create a custom exception class in your application.
Difficulty: MediumType: SubjectiveTopic: Exceptions
You create a custom exception when you need to represent a domain-specific error condition that built-in exceptions don’t model. For example in a banking app you may define `InsufficientFundsException`. The custom exception typically extends a base exception type, adds meaningful context (like account ID, amount) and is thrown when your logic detects the condition. This improves clarity of error handling and makes catch blocks more expressive.
87. Walk through how you would implement robust file I/O handling including exceptions, resource cleanup and logging.
Difficulty: MediumType: SubjectiveTopic: File IO
First, you surround file operations with try or try-with-resources to ensure cleanup. You catch IOException or higher‐level exceptions, log the file path, error nature and maybe retry or fallback. In finally (or automatically via try-with-resources) you close streams. You validate file existence and permissions before opening. In larger systems you might use abstraction over file I/O to inject mock streams for testing. Documenting and propagating meaningful errors completes the pattern.
88. Explain exception propagation, chaining, and best practices when designing APIs for exception handling.
Difficulty: HardType: SubjectiveTopic: Exceptions
When a method does not handle an exception it propagates the exception up the call stack to its caller. You may wrap a low-level exception in a higher-level custom one (exception chaining) to add context while preserving original stack trace. Design APIs so that you throw meaningful exceptions, don’t leak internal implementation details, document exceptions a method may raise, and avoid over-catching (which hides bugs). Good exception design enables maintainable and clear error handling.
89. Compare binary I/O and text I/O in object-oriented programming context and when you would choose one over the other.
Difficulty: HardType: SubjectiveTopic: File IO
Text I/O handles human-readable formats (like JSON, XML, CSV) and is easier for debugging and interoperability. Binary I/O uses raw bytes and is typically faster, more compact and used for images, performance-sensitive data or proprietary formats. For example you may serialize objects into binary form for cache, but write logs as text for readability. In code you might wrap streams accordingly and enforce encoding or endianness. Choosing correctly affects performance, maintainability and error handling.
90. What is a design pattern in object-oriented programming?
Difficulty: EasyType: MCQTopic: Design Patterns
- A fixed algorithm to compute results
- A reusable solution template for a common design problem
- A new programming language feature
- A strict requirement for all classes
A design pattern is a general, reusable solution to a common problem in software design. It is not a finished design that can be directly transformed into code. Rather it provides a template or blueprint for solving problems that occur across many projects.
Correct Answer: A reusable solution template for a common design problem
91. What do creational design patterns deal with?
Difficulty: MediumType: MCQTopic: Pattern Types
- Object composition and relationships
- Object-creation mechanisms and flexibility
- Object-interaction and communication
- Algorithmic complexity
Creational patterns deal with ways to create objects while hiding the creation logic, making the system independent of how its objects are created, composed, and represented.
Correct Answer: Object-creation mechanisms and flexibility
92. Which creational pattern ensures that a class has only one instance and provides a global access point to it?
Difficulty: MediumType: MCQTopic: Singleton Pattern
- Builder
- Prototype
- Factory Method
- Singleton
The Singleton pattern restricts instantiation of a class to one object and provides a global point of access to that instance. It's used when exactly one object is needed to coordinate actions across the system.
Correct Answer: Singleton
93. What is the main idea behind the Factory Method pattern?
Difficulty: MediumType: MCQTopic: Factory Method
- Create complex objects step by step
- Clone existing objects
- Define an interface for creating an object, but let subclasses decide which class to instantiate
- Ensure only one object is created
The Factory Method pattern defines an interface for creating an object, but lets subclasses alter which class is instantiated. This allows for loose coupling by delegating object creation to subclasses.
Correct Answer: Define an interface for creating an object, but let subclasses decide which class to instantiate
94. Which pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes?
Difficulty: HardType: MCQTopic: Abstract Factory
- Builder
- Prototype
- Abstract Factory
- Singleton
The Abstract Factory pattern offers an interface for creating families of related or dependent objects without specifying their concrete classes. It promotes consistency among products and separates client code from concrete implementations.
Correct Answer: Abstract Factory
95. What problem does the Builder pattern solve?
Difficulty: HardType: MCQTopic: Builder Pattern
- Managing a pool of objects
- Creating an object step-by-step allow different representations
- Hiding the creation logic of an object
- Ensuring single instance per class
The Builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. It is useful when an object has many optional parameters or complex construction logic.
Correct Answer: Creating an object step-by-step allow different representations
96. When should you use the Prototype pattern in object-oriented design?
Difficulty: HardType: MCQTopic: Prototype Pattern
- When object creation is trivial
- When you want only one instance globally
- When creating a new object cost is high and you can clone existing instance
- When you need to stream objects over network
The Prototype pattern is used when the type of objects to create is determined at runtime and object creation is expensive. It builds a new object by copying a prototype instance rather than instantiating classes via new.
Correct Answer: When creating a new object cost is high and you can clone existing instance
97. Which technique is commonly used in creational patterns to defer object creation until it is needed?
Difficulty: MediumType: MCQTopic: Object Lifecycle
- Eager loading
- Lazy initialization
- Static allocation
- Singleton locking
Lazy initialization delays creation of an object until it is actually required. This is a common approach in creational patterns to optimize performance and resource usage, especially when object creation is expensive or the object may not be used.
Correct Answer: Lazy initialization
98. Why are design patterns considered important in software engineering?
Difficulty: MediumType: SubjectiveTopic: Design Patterns
Design patterns encode proven solutions to recurring design problems, which saves development time and improves code quality. /n/n They provide a common vocabulary among developers so one can refer to a pattern name and instantly understand the structure and intent. /n/n They help promote code reuse, loose coupling, maintainability and scalability by guiding developers to structure relationships between objects rather than re-inventing solutions.
99. What are some trade-offs when using design patterns and when should you avoid applying them?
Difficulty: HardType: SubjectiveTopic: Design Tradeoffs
While design patterns provide clear benefits, they also introduce abstraction layers which may increase complexity and reduce clarity if used indiscriminately. /n/n Over-engineering with too many patterns can lead to code bloat, harder debugging and performance overhead. /n/n You should avoid applying a pattern when a simpler solution suffices and only adopt a pattern when it clearly matches a recurring problem in the system.
100. Explain some pitfalls of the Singleton pattern and how you would mitigate them in real-world applications.
Difficulty: MediumType: SubjectiveTopic: Singleton Pattern
The Singleton pattern restricts a class to one instance, but this may introduce hidden dependencies and make unit testing difficult because the global instance persists and can retain state. /n/n It may hinder parallelism, and misuse can turn it effectively into a global variable which violates encapsulation. /n/n To mitigate this you can use dependency injection (inject the singleton instance rather than letting classes call the static getInstance), avoid using Singleton for excessive state, and ensure thread-safe initialization (e.g., using double-checked locking or enum singletons in Java).
101. Compare the Factory Method and Builder patterns and describe scenarios where each is more appropriate.
Difficulty: HardType: SubjectiveTopic: Pattern Compare
The Factory Method pattern is about defining an interface for creating an object but letting subclasses decide which class to instantiate. It is useful when you want to vary the concrete implementation based on runtime conditions. /n/n The Builder pattern, on the other hand, is about constructing a complex object step-by-step, where you might want optional parameters, fluent interface, or different representations of the same product. /n/n Use a Factory when you have a single method that returns varied subclasses; use a Builder when you need to build complex objects with many options or deviate from simple constructors.
102. What is the primary focus of structural design patterns?
Difficulty: EasyType: MCQTopic: Pattern Types
- Object creation mechanisms
- Class and object composition into larger structures
- Communication between objects
- Concurrency control
Structural design patterns are concerned with how classes and objects are composed to form larger structures while keeping these structures flexible and efficient.
Correct Answer: Class and object composition into larger structures
103. What is the primary concern of behavioral design patterns?
Difficulty: EasyType: MCQTopic: Pattern Types
- Object pooling
- Object creation
- Object communication and responsibility distribution
- Object destruction
Behavioral design patterns handle the interaction and assignment of responsibilities between objects and how they collaborate.
Correct Answer: Object communication and responsibility distribution
104. Which structural pattern allows two incompatible interfaces to work together?
Difficulty: MediumType: MCQTopic: Adapter Pattern
- Facade
- Adapter
- Decorator
- Proxy
The Adapter pattern wraps one interface to match another so that clients can work with incompatible classes as if they shared the same interface.
Correct Answer: Adapter
105. Which structural pattern allows you to add responsibilities to objects dynamically?
Difficulty: MediumType: MCQTopic: Decorator Pattern
- Bridge
- Facade
- Decorator
- Flyweight
The Decorator pattern attaches extra responsibilities to objects at runtime without modifying their class. This supports flexible behaviour extension.
Correct Answer: Decorator
106. What is the intent of the Facade pattern?
Difficulty: MediumType: MCQTopic: Facade Pattern
- Provide a simplified interface to a complex subsystem
- Enforce a single instance
- Allow subclassing at runtime
- Queue a chain of commands
A Facade offers a unified, simpler interface that hides the underlying subsystem complexity from clients.
Correct Answer: Provide a simplified interface to a complex subsystem
107. Which behavioral pattern lets an object notify other objects about changes to its state?
Difficulty: MediumType: MCQTopic: Observer Pattern
- Strategy
- Observer
- State
- Prototype
The Observer pattern defines a one-to-many dependency so that when one object changes state, all its dependents are notified and updated automatically.
Correct Answer: Observer
108. Which behavioral pattern enables selecting an algorithm's behavior at runtime?
Difficulty: MediumType: MCQTopic: Strategy Pattern
- Command
- Strategy
- Singleton
- Bridge
The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from the clients that use it.
Correct Answer: Strategy
109. In the Chain of Responsibility pattern, what happens when an object cannot handle a request?
Difficulty: HardType: MCQTopic: Chain Responsibility
- It throws an exception
- It modifies the request and processes it itself
- It passes the request to the next object in the chain
- It discards the request
In Chain of Responsibility, a request is passed along a chain of handlers until one of the objects in the chain handles it. This decouples sender and receiver.
Correct Answer: It passes the request to the next object in the chain
110. Which structural pattern allows you to treat individual objects and compositions of objects uniformly?
Difficulty: HardType: MCQTopic: Composite Pattern
- Visitor
- Composite
- Mediator
- Flyweight
The Composite pattern lets clients treat single objects and compositions of objects the same way, enabling flexible tree-structured representations of part-whole hierarchies.
Correct Answer: Composite
111. Compare the Adapter and Facade patterns and describe scenarios for choosing each.
Difficulty: MediumType: SubjectiveTopic: Pattern Compare
Adapter and Facade are both structural patterns, but they serve different purposes. /n/n Adapter is used when you have existing classes with incompatible interfaces and you need to make them work together. For example, you have a library class that exposes one interface and your code expects another; you write an Adapter to wrap the library class so that it matches your expected interface. /n/n Facade is used when you want to simplify a complex subsystem by providing a single unified interface to it. For instance you expose a `PaymentFacade.processPayment()` method that internally coordinates wiring of multiple classes (gateway, logger, notifier) while the client only deals with the facade. /n/n Choosing Adapter emphasizes compatibility between interfaces; choosing Facade emphasises simplifying usage of complex subsystem.
112. Why are behavioral design patterns important in software design, particularly in object-oriented systems?
Difficulty: MediumType: SubjectiveTopic: Pattern Types
Behavioral patterns help manage how objects communicate and distribute responsibility, rather than focusing just on static structures. /n/n They make it easier to change how interactions happen, to add or swap behaviors without modifying many classes, and to enforce loose coupling between components. /n/n For example, using the Observer pattern you can attach multiple listeners without changing the subject's internal logic; using Strategy you can change the algorithm used by a class at runtime. These capabilities improve flexibility, maintainability and extensibility in object-oriented systems.
113. Discuss trade-offs and pitfalls in applying structural and behavioral design patterns in your projects.
Difficulty: HardType: SubjectiveTopic: Design Tradeoffs
While design patterns lend structure and proven solutions, applying them indiscriminately can lead to added complexity, many small classes, and harder debugging. /n/n Structural patterns may over-abstract composition, making code harder to follow. Behavioral patterns that rely on many indirections (Observer chains or command queues) can introduce performance overhead, debugging challenges, or subtle bugs. /n/n In a live project you should balance pattern application with simplicity: only apply a pattern when it solves a real, recurring problem, and document the design so team members understand why the pattern is present.
114. Explain the Decorator and Proxy patterns, how they differ and when you'd use each in system design.
Difficulty: HardType: SubjectiveTopic: Pattern Compare
The Decorator pattern dynamically attaches responsibilities to an object at runtime without changing its class definition. For example you might wrap a `TextView` with `ScrollDecorator`, `BorderDecorator`, then pass it to a client. Each decorator adds new behaviour. /n/n The Proxy pattern provides a placeholder or surrogate for another object to control access, reduce cost, or add logging/security. For example, a `RemoteProxy` might represent a remote service locally and manage network communication. You'd use Decorator when you need to add flexible behaviour, and Proxy when you need to control access or hide complexity of an object. Knowing these distinctions in interviews shows your depth of design thinking.
115. What does the O in SOLID stand for in object-oriented design?
Difficulty: MediumType: MCQTopic: SOLID
- Object-Oriented
- Open/Closed Principle
- Optimal Design
- Operation-Segregation
In the SOLID acronym (Single responsibility, Open/Closed, Liskov substitution, Interface segregation, Dependency inversion) the 'O' stands for the Open/Closed Principle. The Open/Closed Principle states that software entities should be open for extension but closed for modification.
Correct Answer: Open/Closed Principle
116. Which statement best expresses the Single Responsibility Principle (SRP)?
Difficulty: MediumType: MCQTopic: SOLID
- A class should have many functions to do different jobs
- A class should have only one reason to change
- A class should implement only one interface
- A class should never depend on abstraction
The Single Responsibility Principle means that a class should have only one responsibility, and thus only one reason to change. This keeps classes focused, easier to maintain, and reduces coupling.
Correct Answer: A class should have only one reason to change
117. What is the Liskov Substitution Principle (LSP) concerned with?
Difficulty: HardType: MCQTopic: SOLID
- Classes must implement only one interface
- Subtypes must be substitutable for their base types without affecting correctness
- Classes should have only one method
- Objects should be created via a factory
LSP states that objects of a base type should be replaceable with objects of a derived type without altering the desirable properties of the program (correctness, behaviour, etc.). Violations lead to unexpected behaviour.
Correct Answer: Subtypes must be substitutable for their base types without affecting correctness
118. Which principle is described by "Clients should not be forced to depend on methods they do not use"?
Difficulty: MediumType: MCQTopic: SOLID
- Dependency Inversion Principle
- Interface Segregation Principle
- Open/Closed Principle
- Single Responsibility Principle
The Interface Segregation Principle states that clients should not have to depend on interfaces they do not use. In other words, prefer many specific interfaces over a large general one.
Correct Answer: Interface Segregation Principle
119. Which best describes the Dependency Inversion Principle (DIP)?
Difficulty: HardType: MCQTopic: Dependency Inversion
- High-level modules should depend on low-level modules
- Abstractions should not depend on details; details should depend on abstractions
- Objects must be immutable
- Every class must implement only one interface
The Dependency Inversion Principle says that we should decouple high-level and low-level modules by depending on abstractions rather than concrete classes. This enhances flexibility and testability.
Correct Answer: Abstractions should not depend on details; details should depend on abstractions
120. Which statement best reflects the guideline 'favor composition over inheritance'?
Difficulty: MediumType: MCQTopic: Composition
- Use inheritance as much as possible
- Prefer object composition to extend behaviour rather than deep inheritance chains
- Never use subclasses
- Only compose objects with internal private fields
Favoring composition over inheritance means you build complex behaviour by combining simpler objects (has-a relationship), rather than relying on deep class hierarchies which can increase coupling and fragility. Using composition improves flexibility and maintainability.
Correct Answer: Prefer object composition to extend behaviour rather than deep inheritance chains
121. What is the primary benefit of dependency injection in OOP design?
Difficulty: MediumType: MCQTopic: Dependency Injection
- It forces all classes to be static
- It hides all dependencies completely
- It allows passing dependencies from outside to improve testability and decoupling
- It prevents any inheritance at all
Dependency injection means that an object receives (is injected with) its dependencies rather than creating them internally. This decouples classes and improves testability, as dependencies can be mocked or changed without modifying the class itself.
Correct Answer: It allows passing dependencies from outside to improve testability and decoupling
122. High cohesion and low coupling are considered good design practices. Which phrase best describes low coupling?
Difficulty: MediumType: MCQTopic: Coupling Cohesion
- Modules depend heavily on each other
- Modules are highly independent and changes in one have minimal effects on others
- Modules have no responsibilities
- Modules are isolated and cannot communicate
Low coupling means classes or modules are independent, so modifications in one have minimal impact on others. High cohesion refers to a module having strongly related responsibilities. Together they improve maintainability and scalability.
Correct Answer: Modules are highly independent and changes in one have minimal effects on others
123. What is the main benefit of refactoring code in the context of OOP best practices?
Difficulty: EasyType: MCQTopic: Refactoring
- Making code more complex to impress others
- Improving readability, maintainability and reducing technical debt
- Adding more features indiscriminately
- Removing all comments
Refactoring improves the internal structure of code without changing its behavior. It helps follow best practices (such as SOLID), improves readability and maintainability, and prevents accumulation of technical debt.
Correct Answer: Improving readability, maintainability and reducing technical debt
124. Discuss how you would apply the SOLID principles when designing a medium-scale system in your chosen language.
Difficulty: HardType: SubjectiveTopic: SOLID
When designing a medium-scale system, you first identify the main modules or classes and assign them single responsibilities (SRP). For example you might separate data access, business logic and presentation into distinct classes. /n/n You then design classes to be open for extension but closed for modification (OCP): you use abstract interfaces or base classes so that new behaviours can be added via subclassing or composition rather than editing existing classes. /n/n You ensure that subclasses can substitute for their base classes (LSP): for instance if you have a base `PaymentProcessor` and subclass `CreditCardProcessor`, you must ensure any code referencing `PaymentProcessor` works with `CreditCardProcessor` without change. /n/n Next you apply the Interface Segregation Principle (ISP): you avoid large interfaces that force implementations to implement methods they don't need. Instead you define narrower interfaces for different client needs. /n/n Finally you apply Dependency Inversion Principle (DIP): high-level modules depend on abstractions (interfaces) rather than concrete classes, and you apply dependency injection to decouple modules and improve testability. /n/n By integrating these principles you build a system that is modular, flexible, and maintainable. High cohesion and low coupling further support this goal. Testing and refactoring become easier, new features can be added without changing core classes, and the design remains clean over time.
125. What are some trade-offs when you apply OOP best practices and how do you decide when to use them or avoid over-engineering?
Difficulty: MediumType: SubjectiveTopic: Design Tradeoffs
Applying OOP best practices like SOLID, composition, and dependency injection brings numerous benefits—modularity, testability, and maintainability. /n/n However, there are trade-offs: they often require more classes and abstraction layers, which can increase complexity and reduce clarity. Over-engineering might slow down development, complicate debugging or tie up resources. /n/n You decide to apply them when the system is complex, expected to evolve, or needs to be maintained long-term. For simpler, short-lived scripts or prototypes, you may prefer simpler designs. The key is to balance pragmatism and sound design—not every class needs an interface just because best practice suggests it.
126. Explain how composition improves flexibility compared to inheritance, giving an example.
Difficulty: MediumType: SubjectiveTopic: Composition
Composition means that a class holds references to other classes rather than inheriting from them. This 'has-a' relationship allows behaviour to be changed at run time by replacing composed objects rather than modifying class hierarchy. /n/n For example consider a `Car` class instead of inheriting from `ElectricEngineCar` or `GasEngineCar`, the `Car` class has a reference to `Engine` interface and you can inject `ElectricEngine` or `GasEngine` implementations. This means you can change engine type without changing the Car class or using complex inheritance. /n/n Composition thus supports design flexibility, easier testing (you can mock the engine), and lower coupling than deep inheritance structures.
127. What are a few clean code practices you follow in OOP, and why do they matter?
Difficulty: MediumType: SubjectiveTopic: Clean Code
Clean code practices in OOP include writing small classes with single responsibility, meaningful names, avoiding large methods, favouring composition over inheritance, using interfaces and abstractions, writing tests for behaviour, and refactoring regularly. /n/n These practices matter because they reduce complexity, make the codebase easier to understand and maintain, help new team members onboard quicker, and reduce technical debt over time. They also align with good OOP design principles such as SOLID and ensure that the code evolves smoothly as requirements change.