gpt4 book ai didi

java - 是否可以在 Java 的不同位置创建完全相同的对象?

转载 作者:行者123 更新时间:2023-12-03 23:01:47 26 4
gpt4 key购买 nike

Test d1= new Test();

public static void main(String[] args) {
Test d1 = new Test();
System.out.println(d1);
}

在不同的位置创建同一个对象会发生什么。第一个在类内但在方法外,第二个在同一类的方法内..这可能吗..??代码编译正常,但在运行时有一些异常,如:atTest<init><Test.java:3>

最佳答案

What happens if the same object is created but at different locations?

2 个对象创建。也许,如果你愿意,你不能创建 N 个这样的对象。

The first one inside a class but outside a method and the second one inside a method of the same class. Is it possible?

是的。

最上面的一个充当 Test 类的实例成员,您在该方法中创建的那个是该方法的本地成员。

the code compliles fine but at runtime there is some exception like :at Test

那是stackoverflow错误。您正在尝试在顶层的 Test 类中创建 Test 对象,因此构造函数继续以递归方式调用,因此出现错误。

Exception in thread "main" java.lang.StackOverflowError
at Test.<init>(Test.java:2)

关于java - 是否可以在 Java 的不同位置创建完全相同的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33343767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com