java子类访问父类成员演示程序
时间: 2023-10-02 07:11:28 浏览: 46
下面是一个简单的 Java 程序,演示了子类如何访问父类的成员变量和方法:
```java
// 父类
class Superclass {
int num = 10;
public void display() {
System.out.println("This is the display method of superclass");
}
}
// 子类
class Subclass extends Superclass {
int num = 20;
public void display() {
System.out.println("This is the display method of subclass");
}
public void myMethod() {
Subclass sub = new Subclass();
sub.display();
super.display();
System.out.println("Value of the variable named num in subclass:" + sub.num);
System.out.println("Value of the variable named num in superclass:" + super.num);
}
}
// 测试程序
public class Main {
public static void main(String[] args) {
Subclass obj = new Subclass();
obj.myMethod();
}
}
```
输出结果为:
```
This is the display method of subclass
This is the display method of superclass
Value of the variable named num in subclass:20
Value of the variable named num in superclass:10
```
在子类中,我们可以使用 `super` 关键字来访问父类的成员变量和方法。在上面的 `myMethod` 方法中,我们创建了一个子类的实例 `sub`,并调用了它的 `display` 方法和它的 `num` 变量。接着我们使用 `super` 关键字调用了父类的 `display` 方法和它的 `num` 变量。