简体   繁体   English

覆盖后,如何从另一个方法调用基类自己的方法?

[英]How do I call a base class's own method from another method when it's overridden?

public class Parent{

    private Object oBase;

    public Object getObject(){

        // [some logic] 
        return oBase;
    }

    public String getObjectValue(){

        return getObject().getValue();
    }



public class Child extends Parent {

    private Object oChild;

    public Object getObject(){

        return oChild;
    }


    public Object getObjectValue(){

        return getObject().getValue();
    }

    public String getParentObjectValue(){

        return super.getObjectValue();
    }
}

In the above template, I need a way to make sure that the getObject() in Parent.getObjectValue() calls Parent.getObject() and not Child.getObject(), so that the child class can have getters to oBase and oChild. 在上面的模板中,我需要一种方法来确保Parent.getObjectValue()中的getObject()调用Parent.getObject()而不是Child.getObject(),以便子类可以具有oBase和oChild的吸气剂。

I've tried using ((Parent)this).getObject().getValue() in Parent.getObjectValue(), but it still polymorphs to the child definition. 我试过在Parent.getObjectValue()中使用((Parent)this).getObject()。getValue(),但是它仍然对子定义多态。 Is there way to force static binding in java for a specific call? 有没有办法在特定调用中强制在Java中进行静态绑定?

I'm trying to avoid duplicating the [some logic] from Parent.getObject() in Parent.getObjectValue(), but I guess I'll have to if there's really no way around it. 我试图避免从Parent.getObjectValue()中的Parent.getObject()复制[某些逻辑],但是我想如果真的没有办法的话,我不得不这样做。

You can't force a call to the Parent 's method from outside the child class, due to polymorphism. 由于多态性,您不能从子类外部强制调用Parent的方法。 Indeed, for a Child object, the parent method does not exist anymore, because it has been overriden. 实际上,对于Child对象,父方法已不存在,因为它已被覆盖。

You don't seem to need any aspect of polymorphism here (though it's hard to tell without more information). 您似乎在这里不需要多态性的任何方面(尽管没有更多信息很难说)。 If, indeed, you do not need it (different use cases), then change your methods' names so that it does not happen. 如果确实不需要(不同的用例),请更改方法的名称,以免发生这种情况。

Note: If you're in the child class, then you can use super , but I don't think this is your case. 注意:如果您在子类中,则可以使用super ,但是我不认为这是您的情况。

您可以直接引用私有字段“ oBase”,而不是使用“ getObject()”方法。

You can either make the getObject() method private, or change the method name so that polymorphism will not kick on. 您可以将getObject()方法getObject()私有,也可以更改方法名称,以使多态性不会启动。 Overall, you'll have to rethink your design. 总体而言,您将不得不重新考虑您的设计。

Other options are to extract the [some logic] to a third method and invoke this from both getObject() and getObjectValue() . 其他选项是将[某些逻辑]提取到第三个方法,然后从getObject()getObjectValue()调用此方法。 Please keep in mind the Command Query separation principle when you use this design. 使用此设计时,请记住命令查询分离原则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM