The following program gives output as
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();
}
}
What is the reason?
this is called variable shadowing
and default value of int is 0
make it like
public ParameterizedCtor(int a, int b) {
System.out.println(" I am Parameterized Ctor");
this.a=a;
this.b=b;
}
Also See
this
The un-initialized private variables a and b are set to zero by default. And the overloading c'tctor comes into place.ie, parameterCtor(int a, int b) will be called from main and the local variables a & b are set to 3 and 1, but the class variables a and b are still zero. Hence, a=0, b=0 (default c'tor will not be called).
To set the class variable, use:
this.a = a;
this.b = b;
You need to do this:
public ParameterizedCtor(int a, int b) {
System.out.println(" I am Parameterized Ctor");
this.a=a;
this.b=b;
}
otherwise, you're just re-assigning the a
and b
parameters to themselves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With