[英]Call method from child Class
I am trying something like this: 我正在尝试这样的事情:
public class Dog {
}
public class Cat extends Dog {
private void mew() {
}
}
Dog d = new Dog();
d.mew();
During runtime d will contain a cat object due to other methods but I can't compile. 在运行时,由于其他方法,d将包含cat对象,但我无法编译。
In should initialize Dog
with Cat
instance (or Stone
with SpecialStone
instance): 在应使用
Cat
实例(或用SpecialStone
实例的Stone
)初始化Dog
:
Stone s = new SpecialStone();
Then you can call the method on your SpecialStone
(This can work only if you initialize parent by child class): 然后,您可以在
SpecialStone
上调用方法(仅当您通过子类初始化父级时,此方法才有效):
if (s instanceof SpecialStone) {
(SpecialStone)s.specialMethod();
}
Another way is use of polymorphism: 另一种方法是使用多态:
public class Stone {
public void specialMethod() {
}
}
public class SpecialStone {
@Override
public void specialMethod() {
}
}
But it will add specialMethod
to every instance of Stone
但是它将为每个
Stone
实例添加specialMethod
Its the other way around. 相反。
Dog
is a parent class, so it actually doesn't know that some class Cat
extends it, and it doesn't know about the methods of a classes extending it. Dog
是父类,因此实际上它不知道某个类Cat
扩展,也不知道扩展它的类的方法。
However Cat
extends Dog
and it knows about all non-private methods of a Dog
+ its own methds. 但是
Cat
伸出Dog
,它知道全部的非私有方法Dog
+自己的methds。
So you couldn't call mew()
from Dog
. 因此,您无法从
Dog
调用mew()
。
Use an interface that defines the methods for a "Stone" and then use different implementations for a NormalStone or a SpecialStone. 使用为“ Stone”定义方法的接口,然后对NormalStone或SpecialStone使用不同的实现。 See my example:
看我的例子:
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.