Inheritance & Polymorphism
Difficulty: medium
Overview
Java supports single class inheritance via "extends". Method overriding (runtime polymorphism) requires the same name, parameter list, and a compatible return type. "super" accesses parent constructors and methods. Dynamic dispatch selects the overridden method based on the actual runtime type. Covariant return types allow an overriding method to return a subtype. instanceof checks type compatibility.
Practice Linked Questions
Q1. Which keyword is used to inherit a class in Java?
Select one answer before revealing.
Q2. Method overriding in Java requires that the overriding method:
Select one answer before revealing.
Q3. The 'super' keyword in Java is used to:
Select one answer before revealing.
Q4. Runtime polymorphism in Java is achieved through:
Select one answer before revealing.
Q5. Which of the following are true about method overriding in Java? (More than one answer may be correct)
Select one answer before revealing.
Q6. Polymorphism in Java enables:
Select one answer before revealing.
Q7. Can a constructor be overridden in Java?
Select one answer before revealing.
Q8. Covariant return type in method overriding means:
Select one answer before revealing.
Q9. Which class is the root of the entire Java class hierarchy?
Select one answer before revealing.
Q10. The instanceof operator in Java:
Select one answer before revealing.
Q11. Will the following code compile? If not, why? class Vehicle { Vehicle(String type) { System.out.println("Vehicle: " + type); } } class Car extends Vehicle { Car() { System.out.println("Car"); } }
Select one answer before revealing.
Q12. What is the output of the following code? class Parent { int x = 5; void print() { System.out.println("Parent: " + x); } } class Child extends Parent { int x = 10; void print() { System.out.println("Child: " + x); } } Parent obj = new Child(); obj.print(); System.out.println(obj.x);
Select one answer before revealing.
Q13. What is the output of the following code? class A { A() { show(); } void show() { System.out.println("A.show"); } } class B extends A { int val = 42; B() { super(); } @Override void show() { System.out.println("B.show: " + val); } } new B();
Select one answer before revealing.
Q14. What is the output of the following code? Object obj = "Hello"; System.out.println(obj instanceof String); System.out.println(obj instanceof Object); System.out.println(obj instanceof Integer);
Select one answer before revealing.
Q15. What happens at runtime with the following code? Object obj = Integer.valueOf(42); String s = (String) obj; System.out.println(s.length());
Select one answer before revealing.
Q16. What is the output of the following code? class Parent { static void greet() { System.out.println("Hello from Parent"); } } class Child extends Parent { static void greet() { System.out.println("Hello from Child"); } } Parent obj = new Child(); obj.greet();
Select one answer before revealing.