在Java中调用子类的方法 [英] Call a method of subclass in Java
问题描述
如果我有基类
Base thing = null;
其中有一个子类
class Subclass扩展Base
我将其作为
thing = new Subclass
如何调用一个特别在Subclass中但不在Base中的方法?
ex。
基本
只有方法()
子类
有方法()
和 specialMethod()
方法 specialMethod()
是我要调用的那个。
If I have a base class
Base thing = null;
of which there is a subclass
class Subclass extends Base
and I instigate it as
thing = new Subclass
how would I call a method that is specifically in Subclass, but not in Base?
ex.
Base
has only method()
Subclass
has method()
and specialMethod()
the method specialMethod()
is the one I want to call.
推荐答案
其他人已经提到了如何投射对象以获得问题的答案,但首先要求提出问题指出可能的设计问题。一些可能的原因:
The others have already mentioned how to cast objects to get an answer to your question, but asking that question in the first place points to a possible design problem. Some possible reasons:
- 该方法位置错误。
- 调用该方法的代码方法是在错误的地方。
- 子类不应该扩展另一个类。最好首选组合而不是继承。在继承时,代码应遵循 Liskov替换原则。
- 这些课程是非一致性,他们不仅仅是一个责任,它们应分成多个类。
- The method is in the wrong place.
- The code which calls the method is in the wrong place.
- The subclass should not extend the other class. It's best to prefer composition over inheritance. And when inheriting, the code should follow the Liskov substitution principle.
- The classes are non-cohesive, they have more than one responsibility, and they should be split into multiple classes.
这篇关于在Java中调用子类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!