Q)What is the output of the following Java program?
class A{
A(){
System.out.println("parent class constructor");
}
}//super class
class B extends A{
B(){
System.out.println("child class constructor");
}
}//sub class
class Test{
public static void main(String args[]){
B b=new B();
}
}
Ans:- parent class constructor
child class constructor
Q)When a sub class object is created, which constructor is invoked/executed first?
sub class’ or super class’?
=>whenever a sub class object is created, JVM calls the constructor of that sub class. From within the su
b class constructor, an implicit call(automatic call) is made to the super class zero argument constructor.
Q)What is the output of the following program?
class A{
A(int a){
System.out.println("parent class constructor");
}
}
class B extends A{
B(){
System.out.println("child class constructor");
}
}//sub class
class Test{
public static void main(String args[]){
B b=new B();
}
}
Ans:- The above program causes compilation error.
Reason:- In super class, zero argument constructor is not available.
Note:- To fix this error, make an explicit call to the super class parameterised
constructor.
B(){
super(10);//explicit call to the super class parameterised constructor.
System.out.println("child class constructor");
}
Q)What is the practical need of calling super class parameterised constructor explicitly
from the sub class constructor?
=>To initialize the parent class private variables for the sub class object,
class A{
A(){
System.out.println("parent class constructor");
}
}//super class
class B extends A{
B(){
System.out.println("child class constructor");
}
}//sub class
class Test{
public static void main(String args[]){
B b=new B();
}
}
Ans:- parent class constructor
child class constructor
Q)When a sub class object is created, which constructor is invoked/executed first?
sub class’ or super class’?
=>whenever a sub class object is created, JVM calls the constructor of that sub class. From within the su
b class constructor, an implicit call(automatic call) is made to the super class zero argument constructor.
Q)What is the output of the following program?
class A{
A(int a){
System.out.println("parent class constructor");
}
}
class B extends A{
B(){
System.out.println("child class constructor");
}
}//sub class
class Test{
public static void main(String args[]){
B b=new B();
}
}
Ans:- The above program causes compilation error.
Reason:- In super class, zero argument constructor is not available.
Note:- To fix this error, make an explicit call to the super class parameterised
constructor.
B(){
super(10);//explicit call to the super class parameterised constructor.
System.out.println("child class constructor");
}
Q)What is the practical need of calling super class parameterised constructor explicitly
from the sub class constructor?
=>To initialize the parent class private variables for the sub class object,