【发布时间】:2017-02-21 11:48:36
【问题描述】:
嘿,伙计们,我是 java 编程的新手。我尝试使用 java 类进行实验,我所做的是我创建了一个实例变量 x,然后创建了 y,它复制了 x 的值。 然后我定义了一个构造函数,它将值或 x 作为参数。 现在,当我尝试打印 y 的值时,它的值为 0,而 x 的值为 5。 为什么会出现问题? 当我们使用 new 关键字和构造函数时,只会创建所有实例字段,所以我觉得在我们使用之后
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
/**
*
* @author Mridul
*/
public class Test {
int x;
int y=x;
Test(int a)
{
x=a;
}
void print()
{
System.out.println(x);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Test ob=new Test(5);
ob.print();
System.out.println(ob.y);
// TODO code application logic here
}
}
Output
5
0
当我们使用 new 关键字和构造函数时,只会创建所有实例字段,所以我觉得在我们使用之后
Test ob=new Test(5);
那么只有类(x,y=x) 中的所有代码应该运行并且它不应该产生问题。 请帮忙
【问题讨论】:
-
对于
intx=a是一种copy,对a的任何更改都不会在=之后反映到x(和@987654329 @ 相当于int x = 0) -
但在输出中它给出 x=5 和 y=0
-
... 因为实例字段初始化运行 before 构造函数语句。
-
但我使用的是构造函数和 new 关键字。
标签: java oop object constructor