Java – chaotic example of constructor overloading

The following program output is

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();
    }

}

Why?

Solution

Uninitialized private variables A and B are set to zero by default Moreover, c'tctor is overloaded in place, and the parameters ctor (int a, int b) are set from main and local variables A & B to 3 and 1, but the class variables A and B are still zero Therefore, a = 0, B = 0 (the default value is not called)

To set a class variable, use:

this.a = a;
this.b = b;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>