关于构造方法的理解不是很清楚,请大家指点。
public class Test
{
public static void main(String args[])
{
Person p1 = new Person("A");
Person p2 = new Person("B", "Shanghai");
Student s1 = new Student("C", "S1");
Student s2 = new Student("D", "Shanghai", "S2");
System.out.println(p1.info());
System.out.println(p2.info());
System.out.println(s1.info());
System.out.println(s2.info());
}
}
class Person
{
private String name;
private String location;
Person(String name)
{
this.name = name;
location = "Beijing";
}
Person(String name, String location)
{
this.name = name;
this.location = location;
}
public String info()
{
return "name: " + name + " location: " + location;
}
}
class Student extends Person
{
private String school;
Student(String name, String school)
{
this(name, "Beijing", school);
}
Student(String n, String l, String school)
{
super(n, l);
this.school = school;
}
public String info()
{
return super.info() + " school: " + school;
}
}
程序很简单,但是有一点我不明白,就是在初始化子类的时候不是要先调用父类的构造方法吗?如果没有显式调用,那么系统自动调用默认的不带参数的构造方法。可是Student s1 = new Student("C", "S1");这句执行的时候它的构造方法中没有显式的调用父类的构造方法,且父类中也没有不带参数的构造方法,那么为什么不会出现错误?不解。