this

10 0 0
                                    

this - it refers to the current object being called. Usually it is used when the field has the same with the parameter of the constructor or method known as shadowing. It means that the parameter in either method or constructor is copying the field or property of the class.

===================

class ExampleThis{

    private String name;

    public ExampleThis(String name){

        this.name = name;

    }

}

====================

This can be read as this current object's field's name has a value of a name too.


Explicit constructor invocation - the this keyword can be used to explicitly call or invoke the constructor. Explicitly meaning you provide a default value.

=======================

class ExampleThis2{

    private String name;

   public ExampleThis2(){

        this("John Doe");

    }

    public ExampleThis2(String yourName){

        name = yourName;

    }

}

========================

In this("John Doe") constructor, I was referring to the constructor ExampleThis2(String yourName) and not the no argument constructor. 

Java ProgrammingWhere stories live. Discover now