What is the difference between Class.this and this in Java
Asked Answered
O

4

132

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?

Otho answered 14/4, 2011 at 16:5 Comment(0)
E
179

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; 
        }

    }
}
Electrocorticogram answered 14/4, 2011 at 16:7 Comment(3)
If instead of Person.this.name you just said "return name" will that not work?Cyanotype
@Amit G - in this example, yes, it will work. however, there are times when you need to clarify which "this" you are using (e.g. if there are conflicts in member var names or method names). see Michael's answer for a relevant example.Boreas
One example would be when you have to give a reference to Person.this to another object.Goodness
H
88

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!"
        }
    }
}
Hessian answered 14/4, 2011 at 16:9 Comment(0)
G
14

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

Gerkman answered 14/4, 2011 at 16:7 Comment(0)
A
4

Class.this is useful to reference a not static OuterClass.

To instantiate a nonstatic InnerClass, you must first instantiate the OuterClass. Hence a nonstatic InnerClass will always have a reference of its OuterClass and all the fields and methods of OuterClass is available to the InnerClass.

public static void main(String[] args) {

        OuterClass outer_instance = new OuterClass();
        OuterClass.InnerClass inner_instance1 = outer_instance.new InnerClass();
        OuterClass.InnerClass inner_instance2 = outer_instance.new InnerClass();
        ...
}

In this example both Innerclass are instantiated from the same Outerclass hence they both have the same reference to the Outerclass.

Arakawa answered 25/4, 2013 at 14:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.