SCJP Java OOP and Inheritance 1 — Questions and Answers
Question 1: Which keyword is used in Java to prevent a class from being subclassed?
- abstract
- static
- final (Correct answer)
- sealed
Correct answer: final
The `final` keyword applied to a class prevents any other class from extending it.
Question 2: What is the output of calling a method on an object reference declared as the superclass type but pointing to a subclass instance?
- Superclass method runs
- Subclass method runs due to dynamic dispatch (Correct answer)
- Compilation error
- NullPointerException
Correct answer: Subclass method runs due to dynamic dispatch
Java uses dynamic method dispatch (runtime polymorphism), so the overridden subclass method is called.
Question 3: Which of the following is true about abstract classes in Java?
- They can be instantiated directly
- They must have at least one abstract method
- They cannot have constructors
- They can contain both abstract and concrete methods (Correct answer)
Correct answer: They can contain both abstract and concrete methods
Abstract classes can have both abstract methods (no body) and concrete methods (with body).
Question 4: In Java, what is the result if a subclass defines a static method with the same signature as a static method in its superclass?
- Runtime polymorphism occurs
- Method hiding occurs (Correct answer)
- Compilation error
- The superclass method is deleted
Correct answer: Method hiding occurs
When a subclass defines a static method with the same signature as the superclass, it hides the superclass method rather than overriding it.
Question 5: Which access modifier allows a method to be accessed within the same package and by subclasses in other packages?
- private
- public
- protected (Correct answer)
- default (no modifier)
Correct answer: protected
`protected` grants access within the same package and to subclasses regardless of package.
Question 6: What happens when a subclass constructor does not explicitly call a superclass constructor?
- Compilation error always occurs
- The default no-arg superclass constructor is called implicitly (Correct answer)
- The superclass constructor is skipped
- NullPointerException at runtime
Correct answer: The default no-arg superclass constructor is called implicitly
Java automatically inserts a call to the superclass no-arg constructor (`super()`) as the first statement if not explicitly provided.
Which keyword is used in Java to prevent a class from being subclassed?