Java中的super关键字
时间: 2024-05-03 07:17:08 浏览: 125
在Java中,super关键字用于引用父类中的成员变量、方法和构造方法。具体来说,super可以用于以下三种情况:
1. 引用父类中的成员变量:当子类和父类中存在同名的成员变量时,可以使用super关键字来引用父类中的成员变量。
例如:
```
public class Parent {
int x = 10;
}
public class Child extends Parent {
int x = 20;
void printX() {
System.out.println("Child x: " + x);
System.out.println("Parent x: " + super.x);
}
}
```
在上面的例子中,Child类中定义了一个名为x的成员变量,而Parent类中也有一个名为x的成员变量。在printX方法中,使用super关键字引用了父类中的成员变量x,输出结果为:
```
Child x: 20
Parent x: 10
```
2. 引用父类中的方法:当子类需要调用父类中已经被覆盖的方法时,可以使用super关键字来引用父类中的方法。
例如:
```
public class Parent {
void print() {
System.out.println("Parent");
}
}
public class Child extends Parent {
void print() {
super.print();
System.out.println("Child");
}
}
```
在上面的例子中,Child类覆盖了父类中的print方法,并在方法中使用super.print()来调用父类中的print方法,输出结果为:
```
Parent
Child
```
3. 调用父类中的构造方法:当子类需要在构造方法中调用父类中的构造方法时,可以使用super关键字来调用父类中的构造方法。
例如:
```
public class Parent {
int x;
Parent(int x) {
this.x = x;
}
}
public class Child extends Parent {
int y;
Child(int x, int y) {
super(x);
this.y = y;
}
}
```
在上面的例子中,Child类中定义了一个构造方法,并在构造方法中使用super(x)来调用父类中的构造方法,以初始化父类中的成员变量x。
阅读全文
相关推荐
















