子类构造函数问题

magiclroom 2014-07-26 11:36:43
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());
}
}

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(String name , String school) {
this(name , "beijing" , school);
}
方法第一句应该是 super()啊,因为父类没有无参函数,编译不会通过啊, 为什么通过了 , 求解???(我是新手)
...全文
127 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
lliiqiang 2014-07-28
  • 打赏
  • 举报
回复
可以调用其它构造方法,这样其它构造方法调用父类super方法就相当于自己调用父类构造方法.
vnvlyp 2014-07-27
  • 打赏
  • 举报
回复
你没看到有 this(name , "beijing" , school); 这个吗? 当一个构造函数调用了另一个构造函数时,不会自动添加super(),不然你在这个构造函数内用super构造了一次,在调用的那个构造函数内,难道又重新用super构造一次?
姜小白- 2014-07-27
  • 打赏
  • 举报
回复
子类构造方法的第一行如果使用this 或 super的话,就不会再调用父类默认的构造方法了 this() 表示调用当前类的其他构造方法,super表示调用父类构造方法 两个方法都可以带参数的

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧