What is the difference between Class.this and this in Java What is the difference between Class.this and this in Java java java

What is the difference between Class.this and this in Java


In this case, they are the same. The Class.this syntax is useful when you have a non-static nested class that needs to refer to its outer class's instance.

class Person{    String name;    public void setName(String name){        this.name = name;    }    class Displayer {        String getPersonName() {             return Person.this.name;         }    }}


This syntax only becomes relevant when you have nested classes:

class Outer{    String data = "Out!";    public class Inner{        String data = "In!";        public String getOuterData(){            return Outer.this.data; // will return "Out!"        }    }}


You only need to use className.this for inner classes. If you're not using them, don't worry about it.