Java "this" in constructors

Well, this is a very simple question, I never encoded in java, but I am writing a class for a friend ... Having something like:

class myClass{

    private string name;
    public string getName() {
        return this.name;
    }   
    public void setName (int newValue) {
        this.name = newValue;
    }

    private int number;
    public int getNumber() {
        return this.number;
    }   
    public void setNumber (int newValue) {
        this.number = newValue;
    }
}  

I was thinking of creating a constructor:

public myClass (string name, int numbers) {
    this.name = name;
    this.number = number;
}

My questions:

  • I use the same identifiers for properties as for parameters. Is this. “Get out of trouble here?”
  • Is it better to use dialing methods, and if so, should I use this "."?

Many thanks

+3
source share
6 answers
  • Yes, this avoids name clashes. In the context of the constructor, the name namerefers to the parameter, and the name this.namerefers to the instance field.
  • , "". name number , . , - , .
+6
  • , this .
  • , . , , , . , this, , , .
+2

, ; this. , , .

. , , , , , . , - , , , , . , , , , .

+1
  • . this .

  • get/set , . .

+1

1) scope , this, . var .

- , .

2) , - - , , . DRY (Do not Repeat Yourself).

:

public myClass (string name, int number) {
    setName( name );
    setNumber( number );
}
+1

, this. . , Rogue Wave, Java.

:

"m" "m_"

private string m_name;
private int m_number;
public myClass(string name, int number) {
    m_name = name;
    m_number = number;
}

call parameters with a different name, usually with a single letter or an abbreviated version of the participant name

private string name;
private int number;
public myClass(string nam, int num) {
    name = nam;
    number = num;
}

But I prefer how you use it now this.

0
source

Source: https://habr.com/ru/post/1786809/


All Articles