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

本文介绍了在面向对象编程中子类构造过程中的关键概念,包括如何通过super()调用基类构造方法及this()调用来使用同一类中的其他构造方法。此外还探讨了当子类构造方法未显式调用基类构造方法时系统的默认行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 子类的构造过程中必须调用其基类的构造方法
  • 子类可以在自己的构造方法中使用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());
	}
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值