
































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

































CS-204: Java Object-Oriented Programming Prep with Detailed Rationales Course Code: CS- 204 Course Name: Java Object-Oriented Programming Topic: Inheritance, Polymorphism, Encapsulation, Abstraction, & Memory Architecture Academic Year: 2026/
📋 STUDY CORE TOPICS OUTLINE
📚 TEXTBOOK ALIGNMENT INDEX | Part | Section Module | Question Scope | Primary Core Concept |
| Part 1 | Core Encapsulation & Access Mechanics | Q1 – Q30 | Data Hiding, Access Modifiers, Defensive Copying | | Part 2 | Class Inheritance & Constructor Chaining | Q31 – Q60 | Extension, Super Keyword, Field Shadowing | | Part 3 | Runtime Polymorphism & Dynamic Dispatch | Q61 – Q90 | Method Overriding, Dynamic Binding, Virtual Methods | | Part 4 | Interfaces, Abstract Classes & Immutability | Q91 – Q120 | Abstract Contracts, Multiple Inheritance via Interfaces | | Part 5 | Memory Layout, Casting & SOLID Architecture | Q121 – Q150 | Stack/Heap
In Java, encapsulation is primarily achieved by declaring class fields as private and providing controlled access via public getter and setter methods. What is the primary architectural purpose of enforcing private field access? A. To prevent the Java Virtual Machine from allocating heap space for non-essential primitives B. To enforce data hiding and prevent external code from directly modifying internal state without validation C. To enable automatic type conversion during polymorphic method invocation D. To allow child classes to bypass parent class field validation rules CORRECT ANSWER: B. To enforce data hiding and prevent external code from directly modifying internal state without validation RATIONALE: Encapsulation bundles state (fields) and behavior (methods) together while restricting direct access to object components. Declaring fields private hides internal representations and forces mutations through accessor/mutator methods where validation logic can be strictly executed. Option A is incorrect because access modifiers do not alter memory allocation on the heap. Option C confuses encapsulation with dynamic polymorphism. Option D is false because private fields cannot be directly accessed by child classes at all.
What happens when a subclass attempts to reduce the visibility of an overridden method inherited from a superclass (for example, overriding a public method with a protected implementation)? A. The code compiles normally because subclasses have total structural autonomy B. The compiler issues a compilation error stating that the overriding method cannot assign weaker access privileges C. The Java Virtual Machine converts the method to private at runtime D. The method becomes package-private automatically CORRECT ANSWER: B. The compiler issues a compilation error stating that the overriding method cannot assign weaker access privileges RATIONALE: Java enforces the rule that an overriding method cannot restrict the access privileges of the method it overrides (e.g., overriding a public method as protected or private is illegal). This guarantees the Liskov Substitution Principle: an instance of a subclass must always fulfill the public contract of its superclass. Options A, C, and D are incorrect descriptions of Java compilation rules.
Analyze the Java package and access level matrix below: Based on Java access control rules, which modifier allows access inside the same package and subclasses in different packages , but denies access to non- subclasses in different packages? A. private B. default (package-private) C. protected D. public CORRECT ANSWER: C. protected RATIONALE: As displayed in standard Java access control matrices, protected opens visibility to the declaring class, any class in the same package, and subclasses in different packages. Non-subclasses in different packages ("the world") are explicitly restricted. private is limited to the declaring class; default excludes foreign package subclasses; public allows universal access.
Which statement correctly describes the concept of immutability in Java class design? A. An immutable class must have all fields declared public and static B. An immutable class cannot be instantiated more than once in heap memory C. An immutable class's state cannot be modified after object construction is complete D. An immutable class must inherit from java.lang.Thread CORRECT ANSWER: C. An immutable class's state cannot be modified after object construction is complete RATIONALE: An immutable class (such as java.lang.String or custom immutable classes) ensures that once an instance is constructed, its state cannot change. This is typically implemented by declaring fields private final, avoiding setter methods, and performing defensive copying of mutable references. Option A describes static global constants. Option B describes a Singleton pattern, not immutability. Option D is completely unrelated.
What is the effect of applying the final modifier to a class definition in Java? A. The class cannot be instantiated using the new keyword B. All methods inside the class are automatically marked as abstract C. The class cannot be extended by any other class D. The class can only contain static primitive variables CORRECT ANSWER: C. The class cannot be extended by any other class RATIONALE: Applying final to a class declaration prevents inheritance (subclassing). For example, java.lang.String is a final class to prevent developers from altering core string manipulation behaviors. Option A describes abstract classes. Option B is paradoxical, as final and abstract are mutually exclusive. Option D is incorrect.
A. Omitting all constructors from the class definition B. Providing public getter methods while completely omitting public setter methods C. Marking all methods inside the class with the volatile modifier D. Extending the class from java.lang.ReadOnly CORRECT ANSWER: B. Providing public getter methods while completely omitting public setter methods RATIONALE: A read-only interface is achieved by initializing private state during object construction (via constructors) and exposing access exclusively through getter methods, deliberately omitting mutator (setter) methods. Option A leads to standard default zero-argument construction. Option C relates to multithreaded memory visibility. Option D names a non-existent standard library class.
Which modifier must be applied to an instance variable to ensure it can only be assigned once , typically inside the constructor? A. static B. transient C. final D. synchronized CORRECT ANSWER: C. final RATIONALE: The final keyword applied to a variable makes it single-assignment. A final instance variable must be initialized either at declaration or within every constructor of the class; once assigned, its reference/value cannot be overwritten. Option A creates a class-level variable. Option B excludes fields from serialization. Option D provides thread synchronization locks on methods/blocks.
When design requirements mandate that an inner nested class must access private members of its enclosing outer class, which statement regarding Java access control is correct? A. The inner class can access private members of the outer class directly
B. The outer class must change all private members to public for the inner class to see them C. The inner class must extend the outer class using extends D. Inner classes are strictly prohibited from referencing private outer state CORRECT ANSWER: A. The inner class can access private members of the outer class directly RATIONALE: Nested inner classes share a special relationship with their enclosing outer class, giving them full access to all outer instance variables and methods, including those declared private. Option B is false because access modification is unnecessary. Option C is false because inheritance is not required for inner class access. Option D is incorrect.
Why is defensive copying unnecessary when returning a private java.lang.String field from a class getter? A. String is a primitive primitive type in Java B. String objects are inherently immutable in Java C. The JVM automatically generates defensive copies for all return statements D. String fields are automatically converted to character arrays CORRECT ANSWER: B. String objects are inherently immutable in Java RATIONALE: Because String instances are immutable (their state cannot be modified after instantiation), returning a direct reference to a String field carries no risk of external callers altering the field's internal value. Defensive copying is only required for mutable object references (such as Date, ArrayList, or array types).
What is the consequence of declaring a constructor as private in a Java class? A. The class will fail to compile under all circumstances B. External classes cannot instantiate the class directly using the new operator C. The class becomes readable only by JVM system threads
RATIONALE: this is a reference variable in Java that refers to the current object executing the code. It is commonly used to resolve field shadowing (e.g., this.name = name), call alternative constructors within the same class (this()), or pass the current object reference as an argument. Option C describes super.
Which modifier prevents a field from being serialized when an object is converted into a byte stream using Java's standard Serialization API? A. volatile B. native C. transient D. strictfp CORRECT ANSWER: C. transient RATIONALE: Marking an instance field with the transient keyword instructs the Java serialization framework to bypass that field during serialization. Its value will not be included in the serialized stream, and upon deserialization, it receives default initial values (e.g., null or 0). volatile deals with thread memory visibility; native designates native C/C++ code integration.
Which access level is granted to members of an interface by default if no explicit access modifier keyword is written on a field declaration? A. private static final B. protected final C. public static final D. package-private CORRECT ANSWER: C. public static final RATIONALE: In Java interfaces, all fields are implicitly public, static, and final (compile-time constants), regardless of whether those keywords are explicitly declared. Options A, B, and D contradict Java interface specification rules.
Consider the following Java snippet:
public class Account { private double balance; public void deposit(double amount) { if (amount > 0) { balance += amount; } } }Which principle of Object-Oriented Programming is directly demonstrated by validation checks in the deposit method? A. Dynamic Polymorphism B. Standard Inheritance C. Encapsulation D. Interface Abstraction CORRECT ANSWER: C. Encapsulation RATIONALE: Encapsulation combines state (balance) with operational methods (deposit) and guards state mutations behind explicit validation rules (ensuring amount > 0). This prevents objects from entering invalid states (e.g., negative balances).
Which design practice represents a clear violation of proper encapsulation? A. Exposing private mutable fields through getter methods using defensive copying
B. Java passes primitives strictly by value , creating a copy of the argument value on the stack C. Java converts primitives to Heap objects before execution D. Java blocks primitive parameter mutation via compiler errors CORRECT ANSWER: B. Java passes primitives strictly by value , creating a copy of the argument value on the stack RATIONALE: Java is exclusively pass-by-value. When a primitive (e.g., int, double) is passed to a method, a duplicate copy of the primitive value is pushed onto the frame stack of the invoked method. Modifications inside the method operate on that local stack copy and leave the caller's value unchanged.
When passing an object reference into a Java method, what exact value is passed into the method parameter? A. A copy of the actual object state allocated on the Heap B. A copy of the reference variable ( memory address pointer) by value C. Direct access to the caller's original stack variable pointer D. An immutable view of the class fields CORRECT ANSWER: B. A copy of the reference variable ( memory address pointer) by value RATIONALE: Java passes everything by value. For objects, the "value" being passed is the reference (pointer address) pointing to the object on the Heap. Reassigning the parameter variable inside the method to a new object does not affect the caller's reference variable, but mutating object fields through that copied reference does alter the shared Heap object.
In software design, what is the core structural benefit of maintaining high cohesion and low coupling using encapsulation? A. Ensures all methods are compiled into native C code
B. Increases software modularity, enabling components to be changed without impacting unrelated code C. Eliminates the need for Garbage Collection D. Accelerates primitive array searching algorithms CORRECT ANSWER: B. Increases software modularity, enabling components to be changed without impacting unrelated code RATIONALE: Encapsulation promotes high cohesion (a class has a single focused responsibility) and low coupling (classes depend on abstract public interfaces rather than concrete internal details). This structural isolation makes code modular, maintainable, and easier to refactor without widespread breaking changes.
Which method modifier combination allows a class method to be accessed without instantiating the class while restricting access strictly to classes within the same package? A. public static B. private static C. static (with package-private visibility) D. protected static CORRECT ANSWER: C. static (with package-private visibility) RATIONALE: Marking a method static permits invocation directly on the class name without object instantiation (e.g., ClassName.method()). By omitting explicit modifiers, the method receives default (package-private) access, restricting callers to the same package.
Why is declaring public static mutable variables generally considered poor object- oriented design? A. They consume continuous Heap space and cannot be accessed by static methods B. They act as global variables , breaking encapsulation and introducing non- deterministic state across threads
D. Declaring the collection field as public static CORRECT ANSWER: A. Returning Collections.unmodifiableList(internalList) RATIONALE: Wrapping an internal collection with Collections.unmodifiableList() creates an unmodifiable wrapper view. Read operations function normally, but any mutation attempt (e.g., .add(), .remove()) throws an UnsupportedOperationException, preserving encapsulation without manual deep copying.
In Java, how does the protected access specifier behave regarding package boundaries? A. Accessible everywhere across all packages unconditionally B. Accessible within the same package, and to subclasses in external packages C. Accessible exclusively within external packages via reflection D. Accessible strictly inside the single declaring class file CORRECT ANSWER: B. Accessible within the same package, and to subclasses in external packages RATIONALE: The protected specifier combines package-private access with inherited access: any class inside the same package can access the member, as can any derived subclass located in a different package.
Consider a class where a private field is assigned directly from a constructor parameter:
public class Schedule { private Date start; public Schedule(Date start) { this.start = start; // Line 4 } ## ``` Why does Line 4 represent an **encapsulation flaw**? A. It causes a stack overflow error during compilation B. The caller retains an external reference to the original mutable `Date` object and can modify `Schedule` internal state post-construction C. It forces the constructor to run synchronously D. The `start` parameter must be marked `static` *CORRECT ANSWER:* B. The caller retains an external reference to the original mutable `Date` object and can modify `Schedule` internal state post-construction *RATIONALE:* Storing a direct reference passed into a constructor allows the external caller (who retains that original `Date` reference) to mutate the `Date` object later. To preserve encapsulation, the constructor must make a defensive copy: `this.start = new Date(start.getTime());`. --- #### Question 31 In Java object-oriented mechanics, what reserved keyword is utilized by a derived class to **extend a single base class**? A. `implements` B. `extends` C. `inherits` D. `instanceof` *CORRECT ANSWER:* B. `extends` *RATIONALE:* The `extends` keyword is used in class declarations to establish an inheritance relationship (e.g., `class Child extends Parent`). `implements` is reserved for interfaces, `inherits` is not a Java keyword, and `instanceof` is a type checking operator. --- #### Question 32 Why does Java prohibit **multiple inheritance of classes** (e.g., `class C extends A, B`)? D. The parent class is automatically converted into an interface *CORRECT ANSWER:* B. The code generates a **compilation error** because the default `super()` call cannot be satisfied *RATIONALE:* When a developer defines a parameterized constructor in a superclass, the compiler stops generating the default no-arg constructor. If the subclass does not explicitly call `super(args)` with matching parameters on its first line, the compiler attempts to insert `super()`, which fails because no zero-argument constructor exists in the superclass. --- #### Question 35 Refer to the **constructor chaining** sequence illustrated below: During object instantiation of a subclass, in what order are **constructors executed** along the inheritance chain? A. Derived class constructor body executes *before* the Superclass constructor body finishes B. Base/Superclass constructors execute and complete **from the top down** (root `Object` class down to the concrete Child class) C. Child constructors execute completely in reverse order without calling superclass initializers D. Superclass constructors are skipped if instance fields are primitive *CORRECT ANSWER:* B. Base/Superclass constructors execute and complete **from the top down** (root `Object` class down to the concrete Child class) *RATIONALE:* Construction proceeds top-down. Although execution enters the child constructor first, the child constructor delegates up the chain via `super()` before running its own body. Thus, the superclass constructor body finishes executing *before* the subclass constructor body runs. --- #### Question 36 What is **variable shadowing** in Java inheritance? A. Overriding a superclass public method with a private static method B. Declaring a field in a subclass with the **exact same name** as a field in its superclass C. Casting an object reference to an un-related interface D. Deleting parent instance variables during runtime compilation *CORRECT ANSWER:* B. Declaring a field in a subclass with the **exact same name** as a field in its superclass *RATIONALE:* Variable shadowing occurs when a subclass defines an instance variable with the exact name as a variable in its superclass. Unlike methods (which are polymorphic and overridden), fields are **not polymorphic**. The subclass field hides (shadows) the superclass field, and access is determined strictly by the reference type. --- #### Question 37 Consider the following code: ```java class Parent { int x = 10; } class Child extends Parent { int x = 20; } Parent obj = new Child(); System.out.println(obj.x);What value will be printed to the console? A. 20 B. 10 C. 0 D. Compilation Error CORRECT ANSWER: B. 10 RATIONALE: Member variables in Java do not exhibit dynamic polymorphic behavior. Variable access is resolved at compile time based on the declared reference type (Parent), not the actual runtime object type (Child). Since obj is of reference type Parent, obj.x resolves to Parent.x, printing 10.