0

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.

Engineering Mind
  • 113
  • 3
  • 12
  • 2
    You should do some research on inheritance concepts – jhamon Feb 13 '20 at 16:37
  • 1
    See this [answer](https://stackoverflow.com/a/10508202/11434552), there is an implicit call to `super` for every class in `Java` at the start of the constructor. – Nexevis Feb 13 '20 at 16:39
  • 2
    Does this answer your question? [Java: Why does my class automatically inherits constructor from superclass?](https://stackoverflow.com/questions/23899863/java-why-does-my-class-automatically-inherits-constructor-from-superclass) – jhamon Feb 13 '20 at 16:40
  • 1
    this inheritance topic name is "chain of inheritance" you can search about it on google for better understanding. – Uzair Feb 13 '20 at 16:41

1 Answers1

2

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

Isaí Hinojos
  • 172
  • 2
  • 11
  • 1
    The constructors of *every* class in the hierarchy between `Object` and the class itself are executed, starting with `Object`. – kaya3 Feb 13 '20 at 16:51