提问人:Ankit 提问时间:3/22/2022 更新时间:3/22/2022 访问量:143
为什么这在没有扩展的构造函数中工作,但在扩展中不起作用 [duplicate]
Why this is working in constructor without extends but not with extends [duplicate]
问:
我有 2 个代码片段
片段 1
class Test7
{
Test6this t;
Test7(Test6this t)
{
System.out.println("entering");
this.t=t;
System.out.println(t);
}
}
public class Test6this {
Test6this()
{
Test7 t7=new Test7(this);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test6this t=new Test6this();
System.out.println("main:"+t);
}
}
片段 2
class Test7
{
Test6this t;
Test7(Test6this t)
{
this.t=t;
System.out.println(t);
}
}
public class Test6this extends Test7{
Test6this()
{
super(this);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test6this t=new Test6this();
System.out.println("main:"+t);
}
}
第一个正在工作,但第二个给出错误 在显式调用构造函数时不能引用“this”或“super”
但是在这两种情况下,我们都在 Test6this 类中使用它,因此在创建 Test6this 的对象之前调用 Test7 的构造函数,然后片段 1 如何工作ign,片段 2 不工作
请帮帮我。 提前致谢
答:
1赞
RealSkeptic
3/22/2022
#1
显式构造函数调用是指使用构造函数或在构造函数内部将构造降级到另一个构造函数或父类的构造函数,如 JLS 项 8.8.7.1 中所定义。this(...)
super(...)
如果你进一步阅读该项目,你会看到:
构造函数体中的显式构造函数调用语句不得引用此类或任何超类中声明的任何实例变量或实例方法或内部类,也不得在任何表达式中使用 this 或 super;否则,将发生编译时错误。
基本上,当您仍在构造对象时,您不能将其或其任何成员用作同一对象的另一个构造函数的参数。
它基本上是尝试在已经构建对象时循环构建对象。
与第一个片段的区别在于,在第一次片段中,瞬间是一个不同的对象,被分配到其他地方。你正在向它传递一个部分构建,但没有自我引用她。Test7
Test6This
在第二个代码段中,该对象与正在构建的对象相同。它不是一个单独的实例,它只是同一对象的不同视图。所以你正在传递它本身。上述规则可以防止这种情况发生。Test7
评论
new Test7(this);
super(this);
super
super()
this
super()
new Test7(this);