Using another constructor in Java

consider:

int a = 0;
    int b = 3;

    //Constructor 1
    public ClassName (int a) {
        this(a,b); //Error
        //new ClassName(a,b) //No error
    }

    //Constructor 2
    public ClassName (int a,int b) {
        this.a = a;
        this.b = b;
    }

First question:

I got an error saying "B should be static" Why can't I use the default value of B (3) in this way?

Second question:

In the first constructor, if I use the comment section, I won't receive an error Is this acceptable?

Solution

When using variables in a class, it is important to pay attention to the validity of the scope You have instantiated the new a, B variables You deceive yourself into believing that these are the same variables In fact, they are in another address space If you want to use your class variable, you must take the parameter out of the function Then they will synchronize with your class instead of isolating parameters a and B into the scope of your function,

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
分享
二维码
< <上一篇
下一篇>>