Re: Base class - Derived class interaction question
- From: "Daniel" <the.doag@xxxxxxxxx>
- Date: 11 Mar 2007 13:46:49 -0700
On Mar 11, 9:59 am, "Chris Uppal" <chris.up...@xxxxxxxxxxxxxxxxxxx
THIS.org> wrote:
Daniel wrote:
What's
throwing me off is that the plus method has to return a reference of
the _derived_ type, which is seemingly impossible if I'm implementing
the method in the base class.
If you think about it you'll see that this is impossible. You want to do two
incompatible things at once
- inherit the code from the superclass
- have that inherited code do something different
There /are/ languages which work like that (where inherited stuff is not merely
inherited but redefined in the subclass), but Java doesn't have the right kind
of type system for that.
The real problem is that the code which creates a new instance does not refer
to the (runtime) class of "this" but the compile-time class where the code is
defined. Since constructors don't inherit it follows that if you want do this
at all (in Java) you /cannot/ use an explicit constructor in the shared code.
(One more example of how explicit constructors cause fragility.)
Following that thought, the nearest you can get is by refactoring to split the
creation of the new object into something that the subclass can override. For
instance, you could make use of the built-in clone() operation, like:
class Base
implements Cloneable
{
Base plus(Base operand)
{
// idiotic try/catch elided for clarity
Base retval = (Base)(this.clone());
retval.value += operand.value;
return retval;
}
}
And then, in the subclass you can override add() to return a Derived, if you
want:
class Derived
extends Base
{
Derived plus(Base operand)
{
return (Derived)(super.plus(operand));
}
}
-- chris
Thanks for the ideas. I like the idea of assigning the object
creation to a construct that can pick the appropriate constructor at
runtime (like the clone method) as oppose to to using the constructor,
which, as Chris pointed out, is doomed to use the base class code even
if the calling instance is of derived type.
I would still be interested as to whether there are any design
patterns or generics tricks that I could use to accomplish similar
means without having to change or add any code to the derived classes
at all. Not an urgent request or anything, just curious (not that it
being urgent would change things from other posters' POVs :-)).
I appreciate everyone's help!
- Daniel
.
- References:
- Base class - Derived class interaction question
- From: Daniel
- Re: Base class - Derived class interaction question
- From: Chris Uppal
- Base class - Derived class interaction question
- Prev by Date: NewBee: HashMaps and an Array
- Next by Date: Re: PHP vs. J2EE
- Previous by thread: Re: Base class - Derived class interaction question
- Next by thread: Re: Base class - Derived class interaction question
- Index(es):
Relevant Pages
|
Loading