user11009705
user11009705

Reputation:

Using getters with this. in java

I am doing a project for CS, and I just realized that I do not understand the mechanics behind the this. java reference and getters. Specifically, if I have the following:

class Circle{
   private int radius;
}

public Circle(int radius){
   this.radius = radius;
}

public int getRadius(){
   return radius;
}

I really appreciate all the help I can get!

Upvotes: 0

Views: 104

Answers (3)

Actually when you refer to this.radius that means you use a class field variable. Otherwise (in your code) you may re-assign your radius as an argument in a given constructor that is may be unwanted in your case. To distinguish it you must either use different name of a variable or use this.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201487

You don't need this in the constructor if you do not shadow the local name. That is with

public Circle(int r){
    this.radius = r;
}

You can write

public Circle(int r){
    radius = r;
}

The this is only required when it is used to specify which radius you are referring to.

Upvotes: 2

Andronicus
Andronicus

Reputation: 26056

It's because radius is the name of both parameter of constructor and field of the class. To disambiguate those this keyword is used. In case of getter this is not needed, but also won't hurt. Some formatters add this by default, it's equivalent to:

public int getRadius(){
    return this.radius;
}

Upvotes: 3

Related Questions