Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

this

People also ask

What is the difference between this () and this in Java?

In Java, both this and this() are completely different from each other. this keyword is used to refer to the current object, i.e. through which the method is called. this() is used to call one constructor from the other of the same class.

Why this () is used in Java?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

Can we use this () in a method?

The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Yes, you can call methods using it.

What is the difference between this () and super () in Java?

super() acts as immediate parent class constructor and should be first line in child class constructor. this() acts as current class constructor and can be used in parametrized constructors. When invoking a superclass version of an overridden method the super keyword is used.


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.


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.