温馨提示×

java怎么调用父类属性

小亿
167
2023-10-14 07:36:43
栏目: 编程语言

在Java中,可以通过使用super关键字来调用父类的属性。

首先,在子类中创建一个与父类属性相同的属性,然后使用super关键字来引用父类的属性。以下是一个示例:

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.println("子类的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关键字,可以调用父类的属性。

0