java怎么调用父类属性
温馨提示:这篇文章已超过528天没有更新,请注意相关的内容是否还可用!
在Java中,可以通过使用`super`关键字来调用父类的属性。点击查看rintln;}}public class Main {public static void main {Child child = new Child();child.display();}}```在上述示例中,`Child`类继承自`Parent`类,并在`Child`类中创建了一个与父类属性`num`相同的属性。在`display()`方法中,使用`super.num`来调用父类的属性,使用`this.num`来调用子类的属性。
在Java中,可以通过使用`super`关键字来调用父类的属性。
首先,在子类中创建一个与父类属性相同的属性,然后使用`super`关键字来引用父类的属性。以下是一个示例:
```java
class Parent {
protected int num = 10;
}
class Child extends Parent {
private int num = 20;
public void display() {
System.out.println("父类的num:" + super.num);
System.out.p活动:慈云数据爆款香港服务器,CTG+CN2高速带宽、快速稳定、平均延迟10+ms 速度快,免备案,每月仅需19元!! 点击查看rintln("子类的num:" + this.num);
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.display();
}
}
```
在上述示例中,`Child`类继承自`Parent`类,并在`Child`类中创建了一个与父类属性`num`相同的属性。在`display()`方法中,使用`super.num`来调用父类的属性,使用`this.num`来调用子类的属性。
输出结果为:
```
父类的num:10
子类的num:20
```
可以看到,通过使用`super`关键字,可以调用父类的属性。
