【发布时间】:2017-02-16 11:52:52
【问题描述】:
在下面的代码中,我声明了 2 个用户定义的构造函数,一个没有参数,另一个有 3 个参数,在这两个构造函数中,我都为实例变量赋值,当执行 main 方法时,构造函数的输出没有参数为 2,第一种方式中具有 3 个参数的构造函数的 o/p 为 0,但是当我尝试第二种方式时,零参数构造函数的 o/p 为 2,3 参数构造函数的 o/p 为 15,我正在传递创建对象时的参数,现在我不明白为什么第一种方式输出为零。
public class Main {
int x, y, z;
Main() {
x = 2;
y = 2;
z = 2;
}
// first way
Main(int x, int y , int z) {
x = 20;
y = 20;
z = 10;
}
// second way
Main(int x, int y , int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int sub() {
int m;
m = x + y - z;
System.out.println("the value is " + m);
return m;
}
}
以下是主要方法:
package demo;
public class Maintest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Main s = new Main();
int s1 = s.sub();
Main s3 = new Main(10,10,5);
int s2 = s3.sub();
System.out.println(s1);
System.out.println(s2);
}
}
【问题讨论】:
标签: java variables constructor instance