该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
看马士兵老师的javaSE视频教程的时候,他讲到如果在子类中没有显示的调用父类的构造函数,那么默认调用父类的无参构造函数。下面的代码中:s2对象对应的构造函数中没有显示的调用父类的构造函数,所以按上面的理论来讲应当调用Person类的无参构造函数,可是Person类中没有无参构造函数,且自己已经定义了构造函数,系统也不会为他默认增加无参构造函数。为什么运行的时候不显示有错呢?
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;
}
}
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("C","shanghai","S2");
System.out.println(p1.info());
System.out.println(p2.info());
System.out.println(s1.info());
System.out.println(s2.info());
}
}