gpt4 book ai didi

java - 如何从父类获取子类的值

转载 作者:行者123 更新时间:2023-12-02 02:31:59 24 4
gpt4 key购买 nike

我只需要帮助从子类中获取值,这涉及到这种条件下的多态性。

首先假设我有两个类(class)

class Parent{
int i =1;
}

class Child extends Parent{
int x = 5;
}

那么我想要发生的是当我这样做时

父 z = new Child();

我想获取 child 中x的值。

最佳答案

您需要将方法 getValueOfX() 添加到 Parent 并在 Child 中覆盖它。您可以在父级中用它做不同的事情,其中​​一个选项是抛出异常,因此添加到 Parent:

public int getValueOfX() {
throw new UnsupportedOperationException();
}

并在Child中覆盖它

@Override
public int getValueOfX() {
return x;
}

另一个更好的选择是使 Parent 中的方法抽象,但随后您需要使整个类抽象:

abstract class Parent{
int i =1;

abstract public int getValueOfX();
}

关于java - 如何从父类获取子类的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46944557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com