super在java
时间: 2024-06-13 14:00:36 浏览: 10
在Java中,super关键字用于调用父类的构造方法、成员变量和成员方法。它可以在子类中使用,以便访问父类的属性和方法。
1. 调用父类的构造方法:
```java
public class Parent {
public Parent() {
System.out.println("Parent constructor");
}
}
public class Child extends Parent {
public Child() {
super(); // 调用父类的无参构造方法
System.out.println("Child constructor");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
}
}
```
输出:
```
Parent constructor
Child constructor
```
2. 调用父类的成员变量和成员方法:
```java
public class Parent {
public String name = "Parent";
public void print() {
System.out.println("Parent method");
}
}
public class Child extends Parent {
public String name = "Child";
public void print() {
super.print(); // 调用父类的print方法
System.out.println("Child method");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
System.out.println(child.name); // 输出:Child
child.print(); // 输出:Parent method Child method
}
}
```
输出:
```
Parent method
Child method
Child
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)