温馨提示:这篇文章已超过230天没有更新,请注意相关的内容是否还可用!
父类调用子类的属性值可以通过创建子类对象,并将其赋值给父类引用来实现。在Java中,子类继承了父类的属性和方法,因此可以通过父类引用来访问子类的属性。
示例代码如下:
class Parent {
protected int value;
public Parent(int value) {
this.value = value;
}
}
class Child extends Parent {
private String name;
public Child(int value, String name) {
super(value);
this.name = name;
}
public String getName() {
return name;
}
}
public class Main {
public static void main(String[] args) {
Parent parent = new Child(10, "ChildName");
System.out.println(parent.value); // 输出子类的属性值,结果为10
System.out.println(((Child) parent).getName()); // 输出子类的属性值,结果为"ChildName"
}
}
在上述示例中,父类`Parent`有一个属性`value`,子类`Child`继承了父类并新增了一个私有属性`name`。在`Main`类的`main`方法中,通过创建子类对象`Child(10, "ChildName")`并将其赋值给父类引用`Parent parent`,实现了父类调用子类的属性值。通过`parent.value`可以访问子类的属性`value`,输出结果为10;通过`(Child) parent`将父类引用强制转换为子类引用,并调用子类的`getName()`方法,输出结果为"ChildName"。