I might just be unable to google for the right words, but I can't find an answer to the following question.
Is it possible to explicitly set the superclass of a new class instance. E.g. I have a SuperClazz
instance and want to create a new instance of Clazz
which extends SuperClazz
. Can I just do something like this (the code is just what I want to do, it doesn't compile and is not correct):
class Clazz extends SuperClazz{
Clazz(SuperClazz superInstance){
this.super = superInstance;
}
}
You're mixing inheritance and delegation. When an object calls
it doesn't call
doThis
on another object which has the type of the object's superclass. It calls it on himself.this
andsuper
are the same thing.super
just allows to access the version of a method defined in the superclass, and overridden in the subclass. So, changing the super instance doesn't make sense: there is no super instance.The super class is always instantiated implicitly, so you cannot do it — "plant" the super class inside an extending class. What you probably want is a copy constructor.
I think you have some missunderstanding in meaning or terms you are using.
Instance (or object) is what you create using
new Clazz()
at runtime. You cannot change it (unless you are using byte code modification tricks). What yo really want is to create 2 classes: base class and its subclass. Here is the simplest example.If you want to call exlplitly constructor of super class from constructor of subclass use
super()
: class Clazz extends SuperClazz { public Clazz() { super(); } }