"任何人都可以解释我以下java代码的执行流程吗?" 对不起我的误导性陈述......我的问题是......
Main b = new Main();
Run Code Online (Sandbox Code Playgroud)
control转到A类构造函数,然后控件直接转到Main类的override方法
public void PrintFields() {
System.out.println("x = "+x+" y = "+y);
}
Run Code Online (Sandbox Code Playgroud)
为什么编译器没有给出错误,因为没有创建x和y .. !! 我只是对此感到困惑.
什么时候在内存中创建x和y以及何时进行初始化?是控制到达Main类中的以下语句时创建的x和y ?
int x = 1;
int y;
Run Code Online (Sandbox Code Playgroud)
码:
class A
{
public A() {
PrintFields();
}
public void PrintFields() {}
}
class Main extends A
{
int x = 1;
int y;
public Main() {
y = -1;
PrintFields();
}
public void PrintFields() {
System.out.println("x = "+x+" y = "+y);
}
}
class Test
{
public static void main(String[] args) {
Main b = new Main();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
run:
x = 0 y = 0 //why 0 0 ?
x = 1 y = -1 // why 1 -1 ?
BUILD SUCCESSFUL (total time: 0 seconds)
Run Code Online (Sandbox Code Playgroud)
谢谢.
Main b = new Main();
Run Code Online (Sandbox Code Playgroud)
control转到A类构造函数,然后调用Main类的overriden方法
public void PrintFields() {
System.out.println("x = "+x+" y = "+y);
}
Run Code Online (Sandbox Code Playgroud)
此时x和y具有默认值
so x=0, y=0
Run Code Online (Sandbox Code Playgroud)
现在控制来了
int x = 1;
int y;
public Main() {
y = -1;
PrintFields();
}
Run Code Online (Sandbox Code Playgroud)
然后
public void PrintFields() {
System.out.println("x = "+x+" y = "+y);
}
Run Code Online (Sandbox Code Playgroud)
此时x = 1且y = -1
所以输出是
x=1, y=-1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1484 次 |
| 最近记录: |