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.


This Question Belongs to Java Program >> Inheritence

Join The Discussion

Related Questions on Inheritence

What is inheritance in Java?

A. The process of acquiring properties and behaviors of one class by another

B. The process of creating objects

C. The process of encapsulation

D. The process of overloading methods