为什么超类在这个程序中首先被执行——尽管我没有 main 方法?
why superclass gets executed first in this program - although I have no main method?
当我运行以下代码时:
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");
}
}
我得到以下输出:
个人来电
员工电话 1
员工电话 2
教师电话
我想知道为什么它打印超类内容,然后打印下一个子类,然后打印下一个子类,尽管我在 Faculty 子类中有 main 方法。你能告诉我它是如何追踪的吗?
谢谢。
使用继承时,总是执行父的 类 构造函数,无论您的实例是否用于子实例。
当我运行以下代码时:
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");
}
}
我得到以下输出:
个人来电
员工电话 1
员工电话 2
教师电话
我想知道为什么它打印超类内容,然后打印下一个子类,然后打印下一个子类,尽管我在 Faculty 子类中有 main 方法。你能告诉我它是如何追踪的吗?
谢谢。
使用继承时,总是执行父的 类 构造函数,无论您的实例是否用于子实例。