Java set super instance of instance

2019-05-11 11:11发布

问题:

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;
}
}

回答1:

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.



回答2:

You're mixing inheritance and delegation. When an object calls

super.doThis();

it doesn't call doThis on another object which has the type of the object's superclass. It calls it on himself. this and super 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.



回答3:

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.

class SuperClazz {
}

class Clazz extends SuperClazz {
}

If you want to call exlplitly constructor of super class from constructor of subclass use super(): class Clazz extends SuperClazz { public Clazz() { super(); } }