Super 关键字
概述
super 关键字用于访问父类成员。
基本概念
用法
| 用法 | 说明 |
|---|---|
| super.成员 | 访问父类成员 |
| super() | 调用父类构造方法 |
| super(param) | 调用父类带参构造 |
代码示例
访问父类成员
java
public class SuperMemberDemo {
static class Parent {
String name = "Parent";
}
static class Child extends Parent {
String name = "Child";
void print() {
System.out.println("this.name: " + this.name);
System.out.println("super.name: " + super.name);
}
}
public static void main(String[] args) {
new Child().print();
}
}调用父类构造
java
public class SuperConstructorDemo {
static class Parent {
String name;
Parent() {
System.out.println("Parent constructor");
}
Parent(String name) {
this.name = name;
System.out.println("Parent with name: " + name);
}
}
static class Child extends Parent {
int age;
Child() {
super(); // 调用父类无参构造
System.out.println("Child constructor");
}
Child(String name, int age) {
super(name); // 调用父类带参构造
this.age = age;
System.out.println("Child with age: " + age);
}
}
public static void main(String[] args) {
System.out.println("--- 创建第一个对象 ---");
new Child();
System.out.println("--- 创建第二个对象 ---");
new Child("张三", 25);
}
}调用父类方法
java
public class SuperMethodDemo {
static class Parent {
void display() {
System.out.println("Parent display");
}
}
static class Child extends Parent {
@Override
void display() {
System.out.println("Child display - before");
super.display(); // 调用父类方法
System.out.println("Child display - after");
}
}
public static void main(String[] args) {
new Child().display();
}
}注意事项
- 默认调用:构造方法第一行默认 super()
- 必须显式调用:有参构造必须显式调用
- 避免重复:super 用于区分父子类成员
