Consider the code:
class A { A() { System.out.println("A"); } }
class B extends A { B() { super(); System.out.println("B"); } }
What will be printed when 'new B()' is executed?
AB then A
BA then B
COnly B
DCompilation Error
Correct Answer:
B. A then B
EXPLANATION
The super() call invokes the parent class constructor first, printing 'A', then the child constructor completes, printing 'B'.
What will be the output of the following code?
class Parent { void display() { System.out.println("Parent"); } }
class Child extends Parent { void display() { System.out.println("Child"); } }
public class Test { public static void main(String[] args) { Parent p = new Child(); p.display(); } }
AChild
BParent
CCompilation Error
DRuntime Error
Correct Answer:
A. Child
EXPLANATION
This demonstrates runtime polymorphism. Even though p is a Parent reference, it points to a Child object, so the overridden display() method in Child class is executed.
Which of the following correctly describes the relationship between a class and an interface?
AA class extends an interface
BAn interface implements a class
CA class implements an interface
DBoth are interchangeable terms
Correct Answer:
C. A class implements an interface
EXPLANATION
In Java, a class implements an interface. A class extends another class. An interface can extend another interface. This is the correct terminology and relationship structure.