日期:2014-05-20  浏览次数:20619 次

继承中的构造方法问题
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 TestExtends {
public static void main(String[] args){
Student s1 = new Student("C","S1");
Student s2 = new Student("C","shanghai","S2");
System.out.println(s1.info());
System.out.println(s2.info());
}
}


编译过了,运行也没问题。我只想问一点。
Student(String name, String school){
this(name,"beijing",school);

这里不是调用构造方法吗?为什么编译会通过?我记得默认是添加无参数的SUPER()。但是父类没有无参数的构造方法。为什么可以运行?

------解决方案--------------------
你是先调的student的另一个构造方法
而这个够着方法 又调用了父类的
Person(String name,String location){
this.name = name;
this.location = location;
}