java如何在子类中调用父类属性
时间: 2023-05-24 10:03:29 浏览: 1086
和方法?
在Java中,可以使用关键字“super”来在子类中调用父类的属性和方法。具体来说,如果子类想要调用父类的属性,可以使用“super.属性名”的方式;如果想要调用父类的方法,可以使用“super.方法名()”的方式,在括号中传入方法所需的参数。尤其需要注意的是,如果子类中存在和父类同名的属性或方法,则使用“super”关键字来明确要调用的是父类的属性或方法。以下是一个简单的示例:
```
public class Parent {
protected int age = 40;
protected void display() {
System.out.println("I am Parent.");
}
}
public class Child extends Parent {
private int age = 20;
public void display() {
super.display(); // 调用父类的display方法
System.out.println("I am Child.");
}
public void printAge() {
System.out.println("Parent age: " + super.age); // 调用父类的age属性
System.out.println("Child age: " + age); // 调用子类的age属性
}
}
public static void main(String[] args) {
Child child = new Child();
child.display();
child.printAge();
}
```
输出结果:
```
I am Parent.
I am Child.
Parent age: 40
Child age: 20
```
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.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://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)