如何调用基类方法? [英] How to call base class method?

查看:95
本文介绍了如何调用基类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这样声明的类:

public abstract class IdentifiableEntity  {
    public boolean validate() {
        return true;
    }
}

public class PreferenceCategory extends IdentifiableEntity {
    public boolean validate() {
        return true;
    }
}

现在,假设我创建了PreferenceCategory变量,并且我想调用IdentifiableEntity.validate()方法,而不是不是 PreferenceCategory.validate()方法.

Now, let's say I have PreferenceCategory variable created, and I want to call the IdentifiableEntity.validate() method, not the PreferenceCategory.validate() method.

我本以为可以通过强制转换(见下文)来做到这一点,但是它仍然调用了重写的方法:

I would have thought I could do this with a cast (see below), but it still calls the overridden method:

PreferenceCategory cat = new PreferenceCategory();

// this calls PreferenceCategory.validate(), not what I want
((IdentifiableEntity)cat).validate(); 

有什么办法吗?

推荐答案

您不能.最好的选择是在PreferenceCategory中添加另一个方法,该方法将调用super的validate()方法.

You can't. Your best bet is to add another method to PreferenceCategory which calls super's validate() method.

public boolean validateSuper() {
    return super.validate();
}

但是您为什么要这样做?这有点设计味.您可能会发现责任模式链很有趣.

But why would you like to do that? This is a bit a design smell. You may find the chain of responsibilty pattern interesting.

这篇关于如何调用基类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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