0

I have read many answers but I am still not clear on it. Below is the sample code:

package test;

public class ThisDemo {

    int first,second;

public void thisData(int a,int b) {
    first=a;
    second=b;

}

public void showData() {
    System.out.println(first +" "+second);
}
    public static void main(String[] args) {

        ThisDemo demo=new ThisDemo();
        demo.thisData(10, 20);
        demo.showData();

        ThisDemo demo1=new ThisDemo();
        demo1.thisData(100, 200);
        demo1.showData();
    }

}

the above code compiles, runs and gives expected output then what is the point in having this keyword? Is it used only if the class variables and method variables are same? If yes, then is it a standard that is followed?

Varun
  • 67
  • 1
  • 11
  • 3
    You are not using the `this` keyword. You basically prefixed your Class and Methods with that. – Murat Karagöz Feb 24 '20 at 10:14
  • 4
    Does this answer your question? [When should I use "this" in a class?](https://stackoverflow.com/questions/2411270/when-should-i-use-this-in-a-class) – Kevin Feb 24 '20 at 10:15
  • It is true that I haven't used this keyword in the above example however I have mentioned in the last sentence of my question - Is it used only if the class variables and method variables are same?. I can write the above code with or without this keyword so what is the advantage I am getting using this keyword. – Varun Feb 24 '20 at 10:20
  • @Varun Imagine if you are telling someone to do some work, so you tell the person to do **'this'** task. This way you are being more explicit and the person would understand what work do you want to be done. There are certain cases when you need to use `this` keyword to explicitly call what variable you refer to. – Taseer Feb 24 '20 at 11:03

0 Answers0