简体   繁体   中英

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.

I've tried using ((Parent)this).getObject().getValue() in Parent.getObjectValue(), but it still polymorphs to the child definition. Is there way to force static binding in java for a specific call?

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.

You can't force a call to the Parent 's method from outside the child class, due to polymorphism. Indeed, for a Child object, the parent method does not exist anymore, because it has been overriden.

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.

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

You can either make the getObject() method private, or change the method name so that polymorphism will not kick on. 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() . Please keep in mind the Command Query separation principle when you use this design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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