Subject Syllabus Hub96+ MCQs13 Topics

Object-Oriented Programming

OOP paradigms including encapsulation, abstraction, inheritance, polymorphism, design patterns, exception handling, and class architecture.

Topic Syllabus & Revision Notes

High-yield concept summaries, formulas, and common exam pitfalls for each topic.

Topic 1

Module 1: Introduction to Programming Paradigms

Explore different programming paradigms including procedural, object-oriented, functional, and event-driven programming. Understand the advantages of OOP and its application in real-world modeling.

View Cheat Sheet & MCQs
Topic 212 Key Rules

Module 2: Basic Concepts of OOP

# Object-Oriented Programming (OOP) - Master Class Reference A detailed, academic, and exam-oriented study guide focusing on Object-Oriented Programming principles, implementation differences in C++ and Java, and critical university-level pitfalls. --- ## 1. Core Pillars of OOP ### A. Encapsulation (Data Hiding) - **Concept**: Bundling data attributes and member functions that manipulate them into a single logical unit (a Class). - **Purpose**: Achieving data hiding to protect an object's internal state from unauthorized direct access or modification. - **Implementation**: Done via access specifiers (`private`, `protected`, `public`). External classes access private variables only through controlled public getters and setters. ### B. Abstraction (Complexity Hiding) - **Concept**: Hiding internal implementation and showing only essential features to the outside world. - **Purpose**: Reducing complexity and decoupling implementation from interface. - **Implementation**: Done using abstract classes (in C++/Java) and interfaces (in Java). For example, a user knows how to push the accelerator pedal of a car without needing to understand how fuel injection is managed. ### C. Inheritance (Code Reuse & Hierarchy) - **Concept**: The mechanism where a derived subclass acquires attributes and behaviors of a parent base class. - **Types**: - **Single**: Class B extends Class A. - **Multilevel**: Class C extends Class B, which extends Class A. - **Hierarchical**: Class B and Class C both extend Class A. - **Multiple**: Class C extends both Class A and Class B (supported in C++; not supported in Java for classes). - **Hybrid**: A combination of multiple and hierarchical inheritance. ### D. Polymorphism (Multiple Forms) - **Compile-Time (Static) Polymorphism**: Resolved during compilation. - **Function Overloading**: Multiple functions with the same name but different signatures (parameter types or numbers) within the same scope. - **Operator Overloading**: Overloading operators (like `+`, `*`) to perform custom operations on user-defined types (supported in C++; not supported in Java to keep syntax clean). - **Run-Time (Dynamic) Polymorphism**: Resolved at runtime based on the actual object instance. - **Method Overriding**: A derived class provides a specific implementation of a method already declared in its base class with the exact same name, return type, and signature. - **Dynamic Dispatch**: In C++, enabled via the `virtual` keyword, `VTable` (Virtual Table), and `VPtr` (Virtual Pointer). In Java, non-static, non-private methods are virtual by default. --- ## 2. C++ vs Java OOP: Deep Dive Comparison | Feature | C++ | Java | |---|---|---| | **Compilation & Execution** | Compiled directly to native machine code. | Compiled to bytecode; executed inside JVM. | | **Memory Management** | Manual allocation (`new`) and deallocation (`delete`). Destructors clean up resources. | Automatic Garbage Collection (GC) sweeps unreachable objects. No destructors. | | **Pointers** | Explicit support. Memory addresses can be manipulated directly. | No explicit pointer arithmetic. Variables hold references to objects on the heap. | | **Virtual Methods** | Must be declared explicitly using the `virtual` keyword. | All non-static, non-private, non-final methods are virtual by default. | | **Multiple Inheritance** | Supported directly for classes. | Not supported for classes (causes Diamond Problem). Supported for interfaces. | | **Operator Overloading** | Supported. | Not supported (except for string concatenation `+`). | | **Access Specifiers** | `public`, `protected`, `private`. | `public`, `protected`, `private`, and default (package-private). | | **Base Class Initialization** | Done via Constructor Initialization List: `Derived() : Base() {}`. | Done via explicit/implicit `super()` call inside constructor. | --- ## 3. Famous University-Level Pitfalls & Concept Deep Dives ### Pitfall A: The Multiple Inheritance "Diamond Problem" - **The Issue**: Suppose Class A has a method `display()`. Class B and Class C inherit from Class A and override `display()`. Class D inherits from both Class B and Class C (multiple inheritance). When Class D calls `display()`, which parent version should be invoked? This creates ambiguity, known as the Diamond Problem. - **C++ Resolution**: C++ resolves this using **Virtual Inheritance**. Declaring base classes as virtual (e.g., `class B : virtual public A` and `class C : virtual public A`) ensures that Class D inherits only **one** instance of Class A's members. - **Why Java Doesn't Support Multiple Class Inheritance**: To avoid the ambiguity, complexity, and compiler overhead of virtual inheritance tables. Instead, Java allows a class to implement multiple **Interfaces**, which do not hold state. In Java 8+, interfaces can have `default` methods; if a naming conflict occurs, Java forces the implementing class to override and explicitly resolve the method to call (e.g., `InterfaceA.super.method()`). - **Clarification**: Java **does** support **Multilevel** inheritance (A -> B -> C). The restriction is strictly on multiple inheritance of classes. ### Pitfall B: The Empty Class Size Paradox - **C++**: The size of an empty class in C++ is **1 byte** (never 0). This is to ensure that different object instances of the empty class have distinct, unique memory addresses (e.g., `&obj1 != &obj2`). - **Java**: An empty object in Java typically takes **8 to 16 bytes** depending on the JVM architecture (32-bit vs 64-bit). This memory is consumed by the **Object Header**, which stores metadata like the Mark Word (locking, GC age, hashcode) and the Klass Word (pointer to class metadata). ### Pitfall C: Object Slicing in C++ - **The Issue**: Object slicing occurs in C++ when a derived class object is assigned to a base class object **by value** (not by reference or pointer). - **Result**: The extra attributes and behaviors of the derived class are "sliced off" because the base class object cannot accommodate them. - **Example**: `Base b = DerivedObj;` slices the object. `Base& b = DerivedObj;` or `Base* b = &DerivedObj;` preserves polymorphic behavior. - **Java Equivalence**: Java does not suffer from object slicing because Java object variables are references, not values. Assigning a subclass reference to a parent class variable only performs upcasting, leaving the underlying object intact. ### Pitfall D: Virtual Destructors & Memory Leaks in C++ - **The Issue**: If a base class pointer points to a derived class object (e.g., `Base* ptr = new Derived();`) and we execute `delete ptr;`, only the base class destructor is invoked if the destructor is not declared virtual. - **Result**: The derived class destructor is skipped, leading to memory leaks if the derived class allocated dynamic heap memory (e.g., arrays, file streams). - **Resolution**: Always declare the base class destructor as `virtual`: `virtual ~Base() {}`. This ensures the derived class destructor runs first, followed by the base class destructor. - **Java Equivalence**: Java does not have destructors or manual deletion. The Garbage Collector handles heap deallocation, making virtual destructors unnecessary. ### Pitfall E: Can Constructors or Destructors Be Virtual? - **Constructor**: Can **never** be virtual in either C++ or Java. A constructor's purpose is to build an object of an exact type, which requires compile-time binding. Virtual dispatch requires a VPtr, which is only set up *after* the constructor runs. - **Destructor**: Can and **must** be virtual in C++ base classes when polymorphism is applied. Destructors do not exist in Java. --- ## 4. One-Liner Quick-Fire Q&As (High-Yield Interview & Exam FAQ) 1. **Why does Java not support multiple class inheritance?** To eliminate the compiler complexity and method-resolution ambiguity associated with the Diamond Problem. 2. **What is the size of an empty class in C++?** 1 byte, to ensure that every object instance of the class has a unique memory address. 3. **What is the primary cause of object slicing in C++?** Assigning a derived class object to a base class object by value instead of by reference or pointer. 4. **Why are base class destructors declared virtual in C++?** To ensure that the derived class destructor is called and derived members are cleaned up when deleting via a base class pointer. 5. **Why can constructors never be virtual?** Constructors must create an object of an exact type, which requires static binding, and the virtual table pointer (VPtr) is not yet initialized. 6. **In Java, which methods are bound statically at compile time?** Methods marked as `private`, `static`, or `final` are bound statically (Compile-Time binding) because they cannot be overridden. 7. **What is the difference between Aggregation and Composition?** Aggregation represents a weak "has-a" relationship with independent lifetimes, while Composition represents a strong "part-of" relationship where child lifetimes are tied to the parent. 8. **How does C++ resolve the Diamond Problem?** By using virtual inheritance (e.g., `class B : virtual public A`) to ensure only a single shared instance of the common grandparent class is created. 9. **Can an abstract class be instantiated directly?** No, abstract classes are incomplete blueprints and cannot be instantiated; they can only be used as base classes for inheritance. 10. **What is the purpose of a Copy Constructor?** To initialize a new object as an exact copy of an existing object of the same class.

View Cheat Sheet & MCQs
Topic 3

Module 3: Classes and Objects in Detail

Delve into the structure of classes, including data members, member functions, and access specifiers. Understand object creation, memory allocation, constructors, and destructors.

View Cheat Sheet & MCQs
Topic 4

Module 4: Encapsulation and Abstraction

Focus on data hiding through getters and setters, and abstraction using classes. Differentiate between abstract classes and interfaces.

View Cheat Sheet & MCQs
Topic 5

Module 5: Inheritance

Understand the need for inheritance, base and derived classes, and various types of inheritance. Learn about method overriding and the 'super'/'base' keyword, and address the Diamond Problem.

View Cheat Sheet & MCQs
Topic 6

Module 6: Polymorphism

Explore both compile-time (function and operator overloading) and runtime polymorphism (method overriding, virtual functions). Differentiate between early and late binding.

View Cheat Sheet & MCQs
Topic 7

Module 7: Constructors and Destructors Deep Dive

Gain a deeper understanding of constructor overloading, chaining, and copy constructor logic. Explore destructor purposes, garbage collection, and resource management.

View Cheat Sheet & MCQs
Topic 8

Module 8: Static and Final Concepts

Learn about static variables, methods, and blocks, as well as the use of the 'final' keyword for constants and immutable objects.

View Cheat Sheet & MCQs
Topic 9

Module 9: Advanced OOP Concepts

Study advanced topics like association, aggregation, composition, dependency, coupling, and cohesion. Understand object relationships, cloning, and the differences between deep and shallow copies.

View Cheat Sheet & MCQs
Topic 10

Module 10: Exception Handling in OOP

Understand different types of errors and the mechanism of exception handling. Learn to use try-catch-finally blocks, create custom exceptions, and manage exception propagation.

View Cheat Sheet & MCQs
Topic 11

Module 11: OOP Design Principles

Study key OOP design principles including SOLID, DRY, KISS, and YAGNI. Apply these principles to write cleaner and more maintainable code.

View Cheat Sheet & MCQs
Topic 12

Module 12: Design Patterns

Explore various design patterns categorized as creational, structural, and behavioral. Learn about common patterns like Singleton, Factory, Adapter, Decorator, Observer, and Strategy, and the MVC architecture.

View Cheat Sheet & MCQs
Topic 13

Practical Component

Apply learned OOP concepts through hands-on projects such as building a Bank Management System or an Online Shopping Cart.

View Cheat Sheet & MCQs

High-Yield Practice Questions

Sample practice MCQs with step-by-step verified explanations.

Problem #1MEDIUM

Choose the correct statement with respect to interfaces - (i) Java does not support "multiple inheritance" however, it can be achieved by using interfaces. (ii) Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. (iii) To implement multiple interfaces, separate them with a comma (,)

View Verified Answer
Problem #2MEDIUM

Match the following – List - I (i) A method that is used to create an instantiation of a class (ii) A signal that something has happened to stop normal execution of a program (iii) A graphical image that is usually stored in a file (iv) Converting one type of value to another type is called List - II (a) Bitmap (b) Type casting (c) Exception (d) Constructor

View Verified Answer
Problem #3HARD

Consider an undirected un-weighted graph G. Let a breadth first traversal of G be done starting from a node r. Let d(r,u) and d(r,v) be the length of the shortest path from r to u and v respectively in G. If u is visited before v during the breadth first traversal, which of the following statement is correct?

View Verified Answer
Problem #4EASY

Which of the following is not a type of constructor?

View Verified Answer
Problem #5MEDIUM

How many types of polymorphisms are supported by C++?

View Verified Answer
Problem #6MEDIUM

Which of the following principle does queue use?

View Verified Answer
Problem #7HARD

GSM technology was a standard developed by -

View Verified Answer
Problem #8EASY

Which OOP concept is defined as hiding data and exposing only required methods?

View Verified Answer
Object-Oriented Programming - Syllabus, Topic Notes & 96+ MCQs | UpScorer | UpScorer