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

  • 子类的构造过程中必须调用其基类的构造方法
  • 子类可以在自己的构造方法中使用super()调用其基类构造方法。
  1. 使用this()调用本类中的另外的构造方法
  2. 如果调用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());
	}
}


你可能感兴趣的:(JAVA)