Re: Calling a method of a base class that is redefined in a extended class
robbie.desutter@gmail.com wrote:
Hello,
How can I call a method of a base class from a base method whereby the
called method is redefined in a class that extends the base class
To be more concrete, assume the following classes
Class A {
void methodX() {
do_1;
methodY(); // **
}
void methodY() {
do_2;
}
}
Class B extends A {
void methodX() {
super.methodX();
methodY();
}
void methodY() {
do_3;
}
}
If you create an instance of Class B and call methodX on it, do_1 is
executed and next do_3 two times (once called by MethodX of Class A
and once by MethodX of class B). However the first time (line **) I
want to call methodY of class A, in order to get sequence do_1, do_2,
do_3.
Already tried to replace line ** to
((A)this).methodY();
but this doesn't work as the explicit cast to class A of an instance
of class B results in an instance of class B...
How can I solve this problem, preferably without a slow reflection.
Kind regards,
Robbie De Sutter
There are a thousand ways to do it. Here's one:
class B {
methodX() {
do_1;
do_2;
do_3;
}
}
:)
(I know it's not what you need by without more details there isn't much
more to be said).
If you need do_1, do_2, and do_3 to be done in that order, you designed the
code wrong. It's not an issue of how the language works.
If you overide MethodY in the subclass, then you are saying you have
redefined MethodY and you want the super class to use your MethodY instead
of his MethodY. If you didn't want that to happen, you shouldn't have
overriden MethodY. Without being more specific about what your code is
doing, we can't give you much more advice about how to refracture it
correctly.
Maybe the solution is that you shouldn't be subclassing A in the first
place.
Maybe you should be using the has-a relationship instead of the is-a
relationship. Maybe A and B should inherit from a common interface which
defines MethodX and MethodY and class B should simply have a reference to
the Class A object. In which case the code works like this:
interface XY {
void methodX();
void methodY();
}
Class A implements XY {
void methodX() {
do_1;
methodY(); // **
}
void methodY() {
do_2;
}
}
Class B implements XY {
XY objectA;
B(XY a) {
objectA = a;
}
void methodX() {
objectA.methodX();
methodY();
}
void methodY() {
do_3;
}
}
That would make it do what you want but keep a similar structure to what
you already have. Just a thought.
--
Curt Welch http://CurtWelch.Com/
curt@kcwc.com http://NewsReader.Com/