[英]Call method from child Class
我正在嘗試這樣的事情:
public class Dog {
}
public class Cat extends Dog {
private void mew() {
}
}
Dog d = new Dog();
d.mew();
在運行時,由於其他方法,d將包含cat對象,但我無法編譯。
在應使用Cat
實例(或用SpecialStone
實例的Stone
)初始化Dog
:
Stone s = new SpecialStone();
然后,您可以在SpecialStone
上調用方法(僅當您通過子類初始化父級時,此方法才有效):
if (s instanceof SpecialStone) {
(SpecialStone)s.specialMethod();
}
另一種方法是使用多態:
public class Stone {
public void specialMethod() {
}
}
public class SpecialStone {
@Override
public void specialMethod() {
}
}
但是它將為每個Stone
實例添加specialMethod
相反。
Dog
是父類,因此實際上它不知道某個類Cat
擴展,也不知道擴展它的類的方法。
但是Cat
伸出Dog
,它知道全部的非私有方法Dog
+自己的methds。
因此,您無法從Dog
調用mew()
。
使用為“ Stone”定義方法的接口,然后對NormalStone或SpecialStone使用不同的實現。 看我的例子:
public interface Stone {
int getValue();
}
public class NormalStone implements Stone {
@Override
public int getValue() {
return 1;
}
}
public class SpecialStone implements Stone {
@Override
public int getValue() {
return 100;
}
}
public class Game {
public static void main(final String[] args) {
final List<Stone> stones = new ArrayList<>();
stones.add(new NormalStone());
stones.add(new SpecialStone());
for (final Stone stone : stones) {
System.out.println(stone.getValue());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.