(一)基本概念
super
是一个引用变量,用于引用父类对象。当父类和子类有相同的命名方法或属性时,可以通过super
来调用父类中的方法或属性。
1. 调用父类方法
例如,有一个父类Animal
和子类Dog
:
class Animal {
public void eat() {
System.out.println("动物吃东西");
}
}
class Dog extends Animal {
public void eat() {
super.eat(); // 调用父类的eat方法
System.out.println("狗吃骨头");
}
}
在这个例子中,Dog
类重写了eat
方法。通过super.eat()
,Dog
类可以先执行父类Animal
的eat
方法,即输出“动物吃东西”,然后再执行自己的eat
方法中的内容,输出“狗吃骨头”。
2. 调用父类属性
假设父类和子类都有一个名为name
的属性:
class Parent {
String name = "父类名字";
}
class Child extends Parent {
String name = "子类名字";
public void printName() {
System.out.println(super.name); // 输出父类的name属性
System.out.println(this.name); // 输出子类的name属性
}
}
在Child
类的printName
方法中,super.name
会输出“父类名字”,而this.name
会输出“子类名字”。
(二)作为父类构造函数的调用
super
也可以用来调用父类的构造函数,格式为super(参数)
。
1. 注意事项
- 调用
super()
必须是类构造函数中的第一条语句,否则编译不通过。 - 每个子类构造方法的第一条语句,都是隐含地调用
super()
。如果父类没有无参构造函数,那么在编译的时候就会报错。class Father { public Father() { System.out.println("father 无参构造函数"); } public Father(int age) { System.out.println("father 有参构造函数"); } } class Children extends Father { public Children() { // 默认存在,写和不写都行 super(); System.out.println("Child 无参构造函数"); } public Children(int age) { super(age); // 显式调用父类的有参构造函数 System.out.println("Child 有参构造函数"); } }
在
Children
类中,无参构造函数隐含地调用了父类的无参构造函数super()
。而有参构造函数则显式地调用了父类的有参构造函数super(age)
。(三)与this的区别
this
和super
在构造函数中只能有一个,且都必须是构造函数当中的第一行。this()
和super()
都指的是对象,均不能在static
环境中使用(因为static
方法与具体对象无关 可以点击这里去进一步回顾static知识),包括static
变量、static
方法、static
语句块。