将“this”传递给this()o super()

我的问题是:

为什么不能将“this”传递给构造函数的显式调用? 例:

class MyClass { MyClass x; public MyClass(MyClass c){ x=c; } public MyClass(){ this(this); //error } } 

您正在尝试将this的引用从构造函数传递到同一实例上的另一个构造函数。

在Java中,在从对this()super()的隐式或显式调用返回之前,您无法在构造函数中隐式或显式地访问this 。 这是因为超类还没有初始化。

您可能需要在构造函数中复制代码:

 class MyClass { private final MyClass myInstance; public MyClass(MyClass myInstance) { this.myInstance = myInstance; } public MyClass() { this.myInstance = this; } } 

可能有办法使用私有构造函数来破解它,但随后你就会陷入黑客攻击。

以下是解决此限制的方法。

解决方法是将临时holder对象传递给超类构造函数。 然后在超类构造函数完成其工作之后,为临时持有者对象提供对此的引用。

参数delta可用于显示此变通方法的主要缺点 – 如果超类构造函数需要使用该参数该怎么办。

 import java . lang . reflect . * ; import java . util . * ; class Father { public static void main ( String [ ] args ) { ( new Son ( args . length > 0 ) ) . run ( ) ; } Father ( Runnable runnable , boolean delta ) { super ( ) ; if ( delta ) { runnable . run ( ) ; } } } class Son extends Father implements Runnable { private static Map < Thread , TempRunnable > temps = new HashMap < Thread , TempRunnable > ( ) ; private static class TempRunnable implements Runnable { private Son son ; TempRunnable ( ) { super ( ) ; temps . put ( Thread . currentThread ( ) , this ) ; } public void run ( ) { son . run ( ) ; } } Son ( boolean delta ) { // super ( this ) ; // the dream super ( new TempRunnable ( ) , delta ) ; temps . get ( Thread . currentThread ( ) ) . son = this ; } public void run ( ) { System . out . println ( "Hello World" ) ; } }