super关键字

  • 在java类中使用super来调用父类中的指定操作
    • super可用于访问父类中定义的属性
      • 当子类与父类中出现同名的属性时,可以通过“super.属性”来调用父类的属性,若想调用子类的同名属性,使用“this.属性”即可
public class Person {
	protected int id = 001;
	protected String name = "吴";
	protected int age;

	......
}
public class Student extends Person{
	private int id = 002;
	private String schoolName;
	public void show() {
		System.out.println(this.id);
		System.out.println(super.id);
		System.out.println(super.name);
	}
	......
}
  • super可用于访问父类中定义的方法
    • 当子类重写父类的方法以后,可以使用“super.方法()”来调用父类的同名方法
public class Person {
	protected int id = 001;
	protected String name = "吴";
	protected int age;
	public void show() {
		......
	}
	......
}
public class Student extends Person{
	private int id = 002;
	private String schoolName;
	public void show() {
		super.show();
		......
	}
	......
}
  • super可用于在子类构造方法中调用父类的构造器
    • 通过在子类中使用“super(形参列表)”来显式地调用父类中指定的构造器
      • 在构造器内部,“super(形参列表)”必须声明在首行
      • 在构造器内部,“this(形参列表)”或“super(形参列表)”只能出现一个
      • 在构造器中,不显式地调用“this(形参列表)”或“super(形参列表)”其中任何一个,默认调用的是父类空参的构造器
  • 建议:设计一个类时,尽量提供一个空参的构造器
public class Person {
	protected int id;
	protected String name;
	protected int age;
	public Person() {
	
	}
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public Person(String name, int age, int id) {
		this(name, age);
		this.id = id;
	}
	......
}
public class Student extends Person{
	private int id;
	private String schoolName;
	public Student() {
		super();
	}
	public Student(String schoolName) {
		super("吴", 23);
		this.schoolName = schoolName;
	}
	......
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值