1Z0-811 Java Class Design 2 — Questions and Answers
Question 1: Which keyword prevents a class from being subclassed in Java?
- abstract
- static
- final (Correct answer)
- sealed
Correct answer: final
The `final` keyword on a class declaration prevents any other class from extending it.
Question 2: What is the result of calling a non-static method on a null reference in Java?
- Compilation error
- NullPointerException at runtime (Correct answer)
- Returns null
- No-op — nothing happens
Correct answer: NullPointerException at runtime
Invoking an instance method on a null reference throws NullPointerException at runtime.
Question 3: Which access modifier makes a member accessible only within its own class?
- protected
- package-private (no modifier)
- private (Correct answer)
- public
Correct answer: private
`private` restricts visibility strictly to the declaring class itself.
Question 4: Given `class B extends A`, and both define `void print()`, what determines which `print()` runs when called via an `A` reference holding a `B` object?
- The reference type (A)
- The object type (B) — runtime polymorphism (Correct answer)
- Whichever was compiled first
- A random selection at runtime
Correct answer: The object type (B) — runtime polymorphism
Java uses dynamic dispatch: the actual object type (B) determines which overridden method executes at runtime.
Question 5: What is the purpose of the `super()` call inside a constructor?
- To call a sibling class constructor
- To invoke a static initializer block
- To call the parent class constructor (Correct answer)
- To re-execute the current constructor
Correct answer: To call the parent class constructor
`super()` explicitly calls the parent class's constructor and must be the first statement in the child constructor.
Question 6: Which of the following is true about Java interfaces in Java 11?
- Interfaces can have instance fields
- Interfaces can have private methods (Correct answer)
- Interfaces cannot have static methods
- Interfaces can extend classes
Correct answer: Interfaces can have private methods
Since Java 9, interfaces can have private methods to share helper code between default methods.
Question 7: What happens if a class implements two interfaces that declare the same default method without overriding it?
- The first interface's method is used
- Compilation error due to ambiguity (Correct answer)
- The method is silently ignored
- Runtime exception on first call
Correct answer: Compilation error due to ambiguity
If a class inherits two conflicting default methods and does not override the method, a compile-time error occurs.
Which keyword prevents a class from being subclassed in Java?