Vidyalelo
Java Programming · Q33

Inheritence

Programming · Java Programming · question 33

Q33

What is the result of compiling and running the following code? class Base public Base() System.out.print("Base"); public class Derived extends Base public Derived() this("Examveda"); System.out.print("Derived"); public Derived(String s) System.out.print(s); public static void main(String[] args) new Derived();

A.
ExamvedaDerived
B.
ExamvedaBaseDerived
C.
BaseExamvedaDerived
Answer
D.
ExamvedaDerivedBase
E.
Compilation Error

Answer: Option C

Solution

Answer: Option C
Solution:

1. new Derived(); statement executes and invoke the non-parametrized constructor of derived class i.e.
public Derived();
2. As Derived class is a subclass of class Base so super(); executes and calls the super class constructor and prints "Base".
3. After that
this("Examveda"); executes and call the parametrized constructor
public Derived(String s); of Derived class as this always refer to the current object. So, it prints "Examveda".
4. Lastly the print statement executes and prints "Derived"
Hence output is BaseExamvedaDerived.