SCJP Java OOP and Inheritance 2 — Questions and Answers
Question 1: Which of the following correctly describes method overloading in Java?
- Same method name, same parameter list, different return type
- Same method name, different parameter list in the same class (Correct answer)
- Same method name, different parameter list in a subclass
- Changing only the return type of a method
Correct answer: Same method name, different parameter list in the same class
Method overloading requires the same method name but a different parameter list (number, type, or order) within the same class.
Question 2: What is the IS-A relationship in Java OOP?
- Composition
- Aggregation
- Inheritance (Correct answer)
- Encapsulation
Correct answer: Inheritance
The IS-A relationship is established through inheritance — a subclass IS-A type of its superclass.
Question 3: Which of the following is NOT a valid way to achieve polymorphism in Java?
- Method overriding
- Interface implementation
- Method overloading at runtime (Correct answer)
- Superclass reference to subclass object
Correct answer: Method overloading at runtime
Method overloading is resolved at compile time (static binding), so it does not contribute to runtime polymorphism.
Question 4: If class B extends class A and both define `toString()`, which `toString()` is called when `A obj = new B(); System.out.println(obj);`?
- A's toString()
- B's toString() (Correct answer)
- Object's toString()
- Compilation error
Correct answer: B's toString()
Because `toString()` is overridden in B and Java uses dynamic dispatch, B's `toString()` is invoked at runtime.
Question 5: Which Java feature allows a class to inherit behavior from multiple sources without multiple inheritance of classes?
- Abstract classes
- Enums
- Interfaces with default methods (Correct answer)
- Anonymous classes
Correct answer: Interfaces with default methods
Since Java 8, interfaces can have `default` methods, allowing a class to inherit behavior from multiple interfaces.
Question 6: What is the purpose of the `super` keyword when used inside a method body?
- To create a new superclass instance
- To call a superclass constructor only
- To access superclass methods or fields hidden by the subclass (Correct answer)
- To declare a superclass reference variable
Correct answer: To access superclass methods or fields hidden by the subclass
`super` in a method body refers to the superclass, allowing access to its overridden methods or hidden fields.
Which of the following correctly describes method overloading in Java?