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();
}
}
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.
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
In Java, which keyword is used to implement inheritance between classes?
A. inheritsFrom
B. inherits
C. implements
D. extends
A. The class that inherits properties and behaviors
B. The child class
C. The class that is inherited from
D. The class that is marked as "final"
In Java, can a subclass inherit constructors from its superclass?
A. Only if the subclass is marked as "final"
B. Yes, a subclass inherits constructors from its superclass
C. Only if the superclass is marked as "static"
D. Only if the subclass is marked as "final"
Join The Discussion