以下程序输出为
I am Parameterized Ctor a = 0 b = 0
public class ParameterizedCtor { private int a; private int b; public ParameterizedCtor() { System.out.println("I am default Ctor"); a =1; b =1; } public ParameterizedCtor(int a,int b) { System.out.println(" I am Parameterized Ctor"); a=a; b=b; } public void print() { System.out.println(" a = "+a); System.out.println(" b = "+b); } public static void main(String[] args) { ParameterizedCtor c = new ParameterizedCtor(3,1); c.print(); } }
是什么原因?
解决方法
未初始化的私有变量a和b默认设置为零.并且重载c’tctor到位,参数ctor(int a,int b)将从main和局部变量a& b设置为3和1,但类变量a和b仍然为零.因此,a = 0,b = 0(默认值不会被调用).
要设置类变量,请使用:
this.a = a; this.b = b;