代码之家  ›  专栏  ›  技术社区  ›  Engineering Mind

为什么超类首先在这个程序中执行-虽然我没有主方法?

  •  0
  • Engineering Mind  · 技术社区  · 6 年前

    当我运行以下代码时:

    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");
      }
    }
    

    个人电话

    员工电话2

    我想知道为什么它先打印超类内容,然后打印下一个子类,然后打印下一个子类,尽管我在Faculty子类中有main方法。你能告诉我是怎么追踪的吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Isaí Hinojos    6 年前

    在处理继承时,总是执行父类的构造函数,而不管您的实例是否针对子类。