您的位置:首页 > 编程语言 > Java开发

java 类的继承(继承中的关键字)

2015-09-18 15:13 513 查看
子类的构造过程中必须调用其基类的构造方法
子类可以在自己的构造方法中使用super()调用其基类构造方法。

使用this()调用本类中的另外的构造方法
如果调用super,必须写在子类构造方法的第一行

如果子类的构造方法没有显示的调用基类的构造方法,则系统默认调用基类的无参数构造方法
如果子类构造方法中既没有显示调用基类构造方法,而基类中有没有无参构造方法,则编译出错

代码如下:

class Person1 {
private String name;
private String location;

Person1(String name) {
this.name = name;
location = "beijing";
}

Person1(String name, String location) {
this.name = name;
this.location = location;
}

public String info() {
return "naem: " + name + "location: " + location;
}

}

class Student extends Person1 {
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 static void main(String[] args) {
Person1 per1 = new Person1("WANGzq");
Person1 per2 = new Person1("zhang","ShangHai");
System.out.println(per1.info());
System.out.println(per2.info());
Student stu = new Student("wang", "Dalian");
System.out.println(stu.info());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: