本文介绍了参考“这个”而调用超级构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类A,写一个子类B.一个只有一个参数化的构造函数。 B必须调用这个超级构造函数A.
现在我想使用一个Object作为参数。这个对象应该调用B的方法。因此,parameter-object必须保存B的引用或必须是一个内部类。

  public B(){
super。(new parameter(this))
}



现在当我想调用构造函数时... Eclipse说:

我看到的唯一的事情是解决这个问题,是一个set方法,注入this实例到参数对象。我不想编辑超类。



你看到更好的方法。

解决方案

编译器真的阻止你在这里脚下射击自己。 B不是完全构造,直到调用超级构造函数,所以如果你传递这(如果编译器允许它)作为参考,并且它调用B上的方法,B将处于无效状态,并导致各种(实际上,A仍然没有初始化,也没有任何类的链,包括Object)。



显而易见的解决方案是提供B外的功能并将其传递给参数的构造函数。具体的解决方案将取决于具体的问题,但是B内部的静态嵌套类(由于同样的原因它需要是静态的 - 一个内部类有一个对外部类实例的隐式引用)可能提供该功能。也许你需要重新思考参数B和它的超类之间的关系。这一切都取决于情况。


I have a class A and write a subclass B. A has only one constructor which is parameterised. B has to call this super constructor of A. Now I want to use an Object as a parameter. This object should call a method of B. So the parameter-object has to hold a reference of B or has to be an inner class.

public B(){
   super.(new parameter(this))
}

Now when I want to invoke the constructor like... Eclipse says:

The only thing I see to get around this, is a set-method, to inject the "this"-instance into the parameter object. I would not like to edit the super-class.

Do you see any better way around this.

解决方案

The compiler is really preventing you from shooting yourself in the foot here. B isn't fully constructed until after the call to the super constructor, so if you pass this (if the compiler allowed it) as a reference, and it calls a method on B, B would be in an invalid state and cause all kinds of nasty problems (in fact, A is still not initialized, nor any class up the chain, including Object).

The obvious solution is to provide the functionality outside of B and pass that to the constructor of the parameter. Specific solutions will depend on the specific problem, but a static nested class inside B (it needs to be static for the same reason - an inner class has an implicit reference to the outer class instance) could provide that functionality, perhaps. Maybe you need to rethink the relationship between the parameter, B and its super class. It all depends on the case.

这篇关于参考“这个”而调用超级构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 08:36