vendredi 27 février 2015

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!




Aucun commentaire:

Enregistrer un commentaire