Reputation: 10831
I want to pass an instance of a super class to a constructor of a sub class. My first idea was to swap the instance of the super class in the sub class similar to javascripts prototypes, but I was told here that Java does not support swapping the reference of the super instance because there is no super instance per se.
To circumvent this issue I want to use a copy constructur which accepts a super class instance. Then I will have to relink all references manually which on the long run will invite bugs when other people extend the code of the super class and forget the copy constructur in the sub class.
Question: Is there some neat and nice way to copy all references automatically, maybe with some reflection mechanism to prevent future bugs?
Upvotes: 0
Views: 591
Reputation: 691685
You shouldn't copy all the references from the superclass instance to the subclass instance. BTW, all these references should not even be accessible from the subclass, if they are declared as private fields in the superclass (as they should be, generally).
What you probably need is delegation, instead of inheritance:
// Foo is the superclass
private class FooAdapter {
private Foo foo;
public FooAdapter(Foo foo) {
this.foo = foo;
}
public void doThis() {
return foo.doThis();
}
}
FooAdapter could extend Foo or (better) theyr should implement a common interface, but that's not necessarily needed.
If this doesn't answer your problem, please tell us what you want to do, instead of telling us how you want to do it. What's the problem you want to solve?
Upvotes: 1