在Java中调用子类的方法 [英] Call a method of subclass in Java

查看:112
本文介绍了在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:

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆