-2

In what instances would I need to use the this keyword? I have used it before when creating class objects, but I found that I don't really need it. The program would behave the same way whether or not it had a this keyword in front of the variable.

For example, these two versions of the same Circle object I created for demonstration produce the same result when used in the Test class, yet one utilizes the this keyword on its private variables where as the other does not.

Version without the this keyword:

 public class Circle{

    private int radius;

    public Circle(){
        //default radius setting
        radius = 1;
    }

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

    public int getRadius(){
        return radius;
    }

    public void setRadius(int r){
        radius = r;
    }
}

Version with the this keyword:

public class Circle{

    private int radius;

   public Circle(){
        //default radius setting
        this.radius = 1;
    }

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

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

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

The Test class I used to test both objects is:

public class Test{
    public static void main(String[] args){
        Circle c = new Circle();
        System.out.println(c.getRadius());
        c.setRadius(6);
        System.out.println(c.getRadius());
    }
}

Which produces the following output in for both versions of the class Circle when executed in the console:

$ java Test
1
6
Beifong
  • 1
  • 3
  • 2
    This is covered in pretty much *any* half-decent tutorial that explains programming Java. I understand thinking you'll just ask this on Stackoverflow, but that is *not* what Stackoverflow is for (see the [what is on-topic](/help/on-topic) article). Just look this up on this on the internet. – Mike 'Pomax' Kamermans Feb 19 '16 at 00:19
  • http://javabeginnerstutorial.com/core-java-tutorial/this-keyword-in-java/ – vk239 Feb 19 '16 at 00:20
  • Go to google.com. Search up "This keyword java". Here is a good article about it.https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html – Ruchir Baronia Feb 19 '16 at 00:20
  • Why are you using single-letter variable names? – nhgrif Feb 19 '16 at 00:22
  • Thanks for the link guys!! I didn't come across that ask when I searched for the answer before I submitted my question. It's quite helpful! – Beifong Feb 19 '16 at 00:36
  • And nhgrif I usually don't use single-letter variables, I did for the example to keep it short and simple :) – Beifong Feb 19 '16 at 00:37

1 Answers1

0

You would need it in that kind of case :

public void setRadius(int radius){
    this.radius = radius;
}

That's the only way for the compiler to make the difference between the local variable and the member variable

maximede
  • 1,763
  • 14
  • 24