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

问题描述

我有一个A类并编写一个子类B.A只有一个构造函数是参数化的。 B必须调用A的超级构造函数。
现在我想使用Object作为参数。该对象应该调用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))
}

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

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

我唯一看到解决这个问题的方法是使用set方法将this实例注入参数对象。我不想编辑超级班。

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.

推荐答案

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

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).

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

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