Java set super instance of instance

你说的曾经没有我的故事 提交于 2019-12-07 12:10:50

问题


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



来源:https://stackoverflow.com/questions/8667525/java-set-super-instance-of-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!