问题描述
我正在研究一个将两个类的引用相互存储的问题
I was working on a problem to store reference of two classes within each other
例如:
class A {
B b;
A(B b){
this.b = b;}
}
class B {
A a;
B(A a){
this.a = a;}
}
public static void main(String...s){
A a = new A(new B(null));
a.b.a = a;
}
现在,如果我使用下面的语句,而不是上面的初始化:
Now if instead of above initialisation, if I use below statement:
A a = new A(new B(a));
我遇到了一个很明显的错误:
I got below error which is quite obvious:
Main.java:19: error: variable a might not have been initialised
A a = new A(new B(a));
但是如果我在JShell上尝试同样的方法,它就可以正常工作(只是要确保variable a
从未被初始化,所以我在执行该语句之前先检查了variable a
,该语句确认它没有被初始化:
But if I try the same on JShell, it works just fine (Just to be extra sure that variable a
has never been initialized, I checked for variable a
just before executing the statement which confirms that it was not initialized before:
可能是我在这里遗漏了一些东西,但是请问有人可以帮助我了解为什么在JAVA中执行同一条语句会有两种不同的行为.
May be I am missing something here, but can some one please help me to understand why there are two different behaviours of the same statement being executed in JAVA.
了解此问题的一种简单方法是,在Jshell
中允许使用以下语句,但在常规程序中不允许:
A simple way to understand this problem is that below statement is allowed in Jshell
but not in normal program:
var somevar = somevar;
推荐答案
尽管我完全同意@Andreas的回答,这是JShell当前正在使用的初始化方式所期望的,但我与@Dawood的观点相同. JShell应该尽可能接近普通编译器,否则有时可能会不确定,因此使用起来不安全.
Though I totally agree with @Andreas answer above that this is expected with the way initialisation is currently working in JShell, I also have the same view as @Dawood that JShell should work to normal compiler as close as possible, otherwise it can sometime be uncertain and hence unsafe to use.
对于这种特殊情况,我向Oracle提出了一个问题,现在它已被接受为正式bug.您可以在此处跟踪有关此错误的更多信息:
For this particular scenario, I raised an issue with Oracle and it has now been accepted as an official bug. You can track more about this bug here:
https://bugs.java.com/bugdatabase/view_bug .do?bug_id = JDK-8200567
希望此问题将在即将发布的JShell版本中很快得到解决.
Hope that this will be resolved soon in the upcoming releases of JShell.
这篇关于在JShell上执行时,同一语句的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!