我有这两门课
public class B {
int mB = 5;
public int getBValue(){
return mB;
}
}
public class A {
int mA = b.getBValue();
public static void main(String [] args){
B b = new B();
System.out.println(mA);
}
}
编译器提示“找不到符号 b”。我理解代码首先从主方法执行,然后按顺序逐行执行。因此,当编译器读取代码时,它首先进入“B b = new B();
”,然后 b 被定义。这是真的吗?范围有误吗?
我理解的第二个状态:
public class B {
static int mB = 5;
public static int getBValue(){
return mB;
}
}
public class A {
static int mA = B.getBValue();
public static void main(String [] args){
System.out.println(mA);
}
}
此状态工作正常。静态属于类本身,不属于任何对象。所以所有的静态加载和初始化都是在程序运行时进行的。
那么这两种状态之间的关键点在哪里呢?
最佳答案
I understand that code first executing from the main method and line after line in order.
这是完全正确的。但是,来自 main
的变量(或来自任何其他方法)不能在 class A
的字段初始值设定项中使用,这些变量在自己的上下文中执行作为类构造函数的一部分。
when complier read code goes first to
B b = new B();
thenb
become defined it's true
是的,b
已为其范围的其余部分定义,即直到 main
的右大括号为止。
so where the key point between these two state?
从这个练习中得到的教训是,字段初始值设定项可以自由访问静态字段和方法;他们无法访问其他任何内容,包括任何方法的构造函数参数和局部变量。此外,参数和局部变量对于它们自己的方法之外的所有内容都是禁止的。
关于java - 解释一下java代码的执行顺序或优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40728376/