简体   繁体   中英

How can I force a child class to use parent methods when it overrides some of them locally?

So, here's the problem. Suppose I have the following code flow:

public class SomeGrandparent {
    private int x;
    private int y;
    ...
    public void setX(int x) {setting value of x...}
    public void setY(int y) {setting value of y...}
}

public class SomeParent extends SomeGrandparent {
    ...
    public void move() {manipulate object movement via calls to inherited setX and setY}
}

public class SomeChild extends SomeParent {
    ...
    public void setX(int x) {throw exception} //Override method. Child should not be allowed to directly modify X.
    public void setY(int y) {throw exception} //Override method. Child should not be allowed to directly modify Y.
}

Then, later in the program, I have the following:

SomeChild aChild = new SomeChild();
...
aChild.move();

Upon execution, when aChild.move() is called, errors are thrown. Why is it that, in SomeChild , the inherited move() method is using the local overridden setX and setY methods? Is there some way I can have aChild.move() call the move() defined in SomeParent AND use the setX and setY defined in SomeParent as well?

Even if I have the following explicitly defined in SomeChild,

...
public void move() {
    super.move();
}

then aChild.move() still utilizes the local overridden setX and setY in SomeChild . This is driving me nuts. Any help appreciated.

The only solution I can fathom is to copy all the code from SomeParent's move() method and paste it into SomeChild, replacing all its references to setX and setY with super.setX and super.setY. However, this completely defeats the purpose of inheritance to begin with!

Polymorphism will choose the runtime type of the object for calls to setX and setY even if they are called in a superclass that doesn't override those methods.

You can make the methods setX() and setY final in SomeGrandparent so that subclasses such as SomeChild can't override them.

I assume that there is a typo in your code example and that you are making use of Polymorphism, so your real code is something like:

SomeGrandparent aChild = new SomeChild();

And not what you said:

SomeChild aChild = new SomeChild();

Which justify your both issues:

  • You are getting compiler error when aChild.move() is called because move() doesn't exist in SomeGrandparent
  • You are using setX and setY of SomeChild because of their Object's runtime Type as explained per rgettman's answer

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