如何使用super函数,你能给我举一些例子吗
时间: 2024-02-26 21:59:02 浏览: 16
当我们需要在子类中访问父类的属性或方法时,可以使用 super 函数。以下是一些使用 super 函数的例子:
1. 调用父类的构造函数:
```
class Parent {
int x;
Parent(int x) {
this.x = x;
}
}
class Child extends Parent {
int y;
Child(int x, int y) {
super(x);
this.y = y;
}
}
```
在上面的例子中,Child 类继承了 Parent 类,并在构造函数中使用 super(x) 调用了 Parent 类的构造函数,以便完成 Parent 类的初始化工作。
2. 调用父类的方法:
```
class Parent {
void show() {
System.out.println("Parent");
}
}
class Child extends Parent {
void show() {
super.show();
System.out.println("Child");
}
}
```
在上面的例子中,Child 类重写了 Parent 类的 show() 方法,并在方法中使用 super.show() 调用了 Parent 类的 show() 方法,从而实现了对 Parent 类方法的扩展。
3. 访问父类的属性:
```
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void show() {
System.out.println(super.x); // 输出 10
}
}
```
在上面的例子中,Child 类继承了 Parent 类,并定义了一个与 Parent 类同名的属性 x。在 Child 类的 show() 方法中使用 super.x 访问了 Parent 类的属性 x,以便获取父类属性的值。
需要注意的是,当子类中定义了与父类同名的属性或方法时,使用 super 函数可以访问到父类的属性或方法。