Examveda
Examveda

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

D. ExamvedaDerivedBase

E. Compilation Error

Answer: Option C

Solution(By Examveda Team)

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.


Join The Discussion

Related Questions on Inheritence

Which is true?

A. "X extends Y" is correct if and only if X is a class and Y is an interface

B. "X extends Y" is correct if and only if X is an interface and Y is a class

C. "X extends Y" is correct if X and Y are either both classes or both interfaces

D. "X extends Y" is correct for all combinations of X and Y being classes and/or interfaces