There are two ways to reference the instance of a class within that class. For example:
class Person {
String name;
public void setName(String name) {
this.name = name;
}
public void setName2(String name) {
Person.this.name = name;
}
}
One uses this.name
to reference the object field, but the other uses className.this
to reference the object field. What is the difference between these two references?
Class.this
is useful to reference a not staticOuterClass
.To instantiate a nonstatic
InnerClass
, you must first instantiate theOuterClass
. Hence a nonstaticInnerClass
will always have a reference of itsOuterClass
and all the fields and methods ofOuterClass
is available to theInnerClass
.In this example both
Innerclass
are instantiated from the sameOuterclass
hence they both have the same reference to theOuterclass
.You only need to use className.this for inner classes. If you're not using them, don't worry about it.
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.This syntax only becomes relevant when you have nested classes: