Search code examples
javaoopinheritanceconstructorsuper

why superclass gets executed first in this program - although I have no main method?


When I run the following code:

public class Employee extends Person
{ 
   public Employee()
   {
       this("Employee call 1");
       System.out.println("Employee call 2");
   }
   public Employee(String s)
   {
    System.out.println(s); 
   }
}

public class Person
{
   public Person()
   {
     System.out.println("Person call");
   }
}

public class Faculty extends Employee
{
  public static void main(String[] args)
  { 
    new Faculty();
  }
  public Faculty()
  {
    System.out.println("Faculty call");
  }
}

I get the following output:

Person call

Employee call 1

Employee call 2

Faculty call

I wanna know why it prints the superclass content then next subclass then next subclass although I have main method in the Faculty subclass. Can you tell me how is it traced?

Thank you.


Solution

  • When working with inheritance it's always the parent's classes constructors that get executed, regardless if your instance is for the child.