java中构造函数和set,get方法求解释。

例如此代码:
class Test
{
private int num = 1;
Test(int x)
{

}
public void setNum(int x)
{
this.num=x+2;
}
public int getNum()
{
return num;
}
}
class TestDemo
{
public static void main(String[] args)
{
Test t = new Test(1);

System.out.println(t.getNum());

}
}
为什么打印的不是3而是1呢?

你的构造函数里面并没有做任何操作。你定义并初始化num值是1,然后你直接调用了get方法来获取这个初始值,所以就是1啊。除非你在构造函数里面做了类似set方法里面的操作,或者直接在构造函数里面调用set方法。例如:
public class Test {
private int num = 1;
Test(int x) {
// this.setNum(x);
this.num = x + 2;
}
public void setNum(int x) {
this.num = x + 2;
}
public int getNum() {
return num;
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-07-21
Test t = new Test(1);
你创建的对象调用构造函数,但并么有对num赋值,你的构造函数Test(int x)
{

}
在你调用getNum()方法是返回的还是最初 private int num = 1;
赋值的
第2个回答  2013-07-21
这当然啦,你都没调用setNum(),num还是原来初始化的1本回答被提问者采纳
第3个回答  2013-07-21
你都没有调用setNum函数,当然getNum()得到的就是1啊
第4个回答  2013-07-21
get 和 set 是类中的两个方法,你只用了get 方法,当然只是1.
相似回答