Java里super()怎么用
时间: 2023-07-05 07:18:26 浏览: 43
Java 中的 `super()` 也是用于调用父类的构造方法或成员方法。 `super()` 的一般用法是在子类中使用 `super()` 关键字来调用其父类的构造方法或成员方法。
例如,如果有一个父类 `Parent` 和一个子类 `Child`,并且 `Child` 想要调用 `Parent` 中的一个构造方法或成员方法,可以使用 `super()` 来实现:
```java
class Parent {
public Parent() {
System.out.println("This is a constructor from Parent class");
}
public void myMethod() {
System.out.println("This is a method from Parent class");
}
}
class Child extends Parent {
public Child() {
super(); // 调用父类的构造方法
}
public void myMethod() {
super.myMethod(); // 调用父类的成员方法
System.out.println("This is a method from Child class");
}
}
public class Example {
public static void main(String[] args) {
Child child = new Child();
child.myMethod();
}
}
```
在这个例子中,子类 `Child` 继承了父类 `Parent`,并覆盖了其中的一个方法 `myMethod`。在子类中,我们使用了 `super.myMethod()` 来调用父类的 `myMethod` 方法,并在其后添加了子类特有的代码。同时,我们在子类的构造方法中使用了 `super()` 来调用父类的构造方法。
使用 `super()` 的好处是,如果需要修改父类的方法或属性,只需要在父类中修改,而不需要在每个子类中都修改一遍。同时,`super()` 也可以用于多层继承的情况,可以很方便地调用父类或祖先类的方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)