30/01/25 ---------- Constructors during Ineheritance ------------------------------------ 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 child class object is created, which constructor is invoked/executed first? child class' or parent class'? =>Which class object is created, JVM always calls that class constructor only. =>When sub class object is created, JVM calls sub class constructor first. =>From within the sub class constructor, an implicit call is made to the super class zero argument constructor. (as Java compiler writes super()) =>Therefore, code in the super class constructor is executed first after that code written in the sub class constructor is executed. It doesn't mean that parent class constructor is executed first. Note:- Whenever sub class object is created, super class object is not created. 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:- super class doesn't have zero argument constructor. But from within the sub class, an implicit call is made to the sub class constructor. To fix the error we can make an explicit call to the super class parameterised constructor from within the sub class constructor class A{ A(int a){ System.out.println("parent class constructor"); } } class B extends A{ B(){ super(10);//explicit call to super class parameterised constructor System.out.println("child class constructor"); } }//sub class class Test{ public static void main(String args[]){ B b=new B(); } } Q)What is the practical need of calling super class parameterised constructor explicitly from the sub class constructor? =>to initialize the super class private variables of sub class object. Example Program ------------------- class Person{ private int age; Person(int age){ this.age=age; } protected void displayPerson(){ System.out.println("Age is "+age); } } class Employee extends Person{ int empno; Employee(int empno,int age){ super(age); this.empno=empno; } void displayEmployee(){ System.out.println("EMPNO:"+empno); this.displayPerson(); } } class ConstructorsInInheritance{ public static void main(String[] args){ Employee e=new Employee(101,25); e.displayEmployee(); } } Q)Give me a scenario when a constructor of a class is executed but its object is not created. =>Whenever sub class object is created, super class constructor is called but super class object is not created.