Java this: dove e come usarlo?

In questo articolo, impareremo a conoscere questa parola chiave in Java, come e dove usarla con l'aiuto di esempi.

questa parola chiave

In Java, questa parola chiave viene utilizzata per fare riferimento all'oggetto corrente all'interno di un metodo o di un costruttore. Per esempio,

 class Main ( int instVar; Main(int instVar)( this.instVar = instVar; System.out.println("this reference = " + this); ) public static void main(String() args) ( Main obj = new Main(8); System.out.println("object reference = " + obj); ) )

Uscita :

 questo riferimento = Main @ 23fc625e riferimento oggetto = Main @ 23fc625e

Nell'esempio sopra, abbiamo creato un oggetto chiamato obj della classe Main. Quindi stampiamo il riferimento all'oggetto obj e alla thisparola chiave della classe.

Qui, possiamo vedere che il riferimento di obj e thisè lo stesso. Significa che questo non è altro che il riferimento all'oggetto corrente.

Uso di questa parola chiave

Esistono varie situazioni in cui la thisparola chiave viene comunemente utilizzata.

Usandolo per i nomi delle variabili di ambiguità

In Java, non è consentito dichiarare due o più variabili con lo stesso nome all'interno di uno scope (ambito di classe o ambito di metodo). Tuttavia, i parametri e le variabili di istanza possono avere lo stesso nome. Per esempio,

 class MyClass ( // instance variable int age; // parameter MyClass(int age)( age = age; ) )

Nel programma sopra, la variabile di istanza e il parametro hanno lo stesso nome: età. Qui, il compilatore Java è confuso a causa dell'ambiguità del nome.

In una situazione del genere, utilizziamo questa parola chiave. Per esempio,

Per prima cosa, vediamo un esempio senza usare la thisparola chiave:

 class Main ( int age; Main(int age)( age = age; ) public static void main(String() args) ( Main obj = new Main(8); System.out.println("obj.age = " + obj.age); ) )

Uscita :

 mc.age = 0

Nell'esempio precedente, abbiamo passato 8come valore al costruttore. Tuttavia, stiamo ottenendo 0come output. Questo perché il compilatore Java viene confuso a causa dell'ambiguità nei nomi tra l'istanza della variabile e il parametro.

Ora, riscriviamo il codice sopra usando la thisparola chiave.

 class Main ( int age; Main(int age)( this.age = age; ) public static void main(String() args) ( Main obj = new Main(8); System.out.println("obj.age = " + obj.age); ) )

Uscita :

 obj.age = 8

Ora stiamo ottenendo l'output previsto. È perché quando viene chiamato il costruttore, thisall'interno del costruttore viene sostituito dall'oggetto obj che ha chiamato il costruttore. Pertanto alla variabile età viene assegnato il valore 8.

Inoltre, se il nome del parametro e della variabile di istanza è diverso, il compilatore aggiunge automaticamente questa parola chiave. Ad esempio, il codice:

 class Main ( int age; Main(int i) ( age = i; ) )

è equivalente a:

 class Main ( int age; Main(int i) ( this.age = i; ) )

questo con Getters e Setters

Un altro uso comune della thisparola chiave è nei metodi setter e getter di una classe. Per esempio:

 class Main ( String name; // setter method void setName( String name ) ( this.name = name; ) // getter method String getName()( return this.name; ) public static void main( String() args ) ( Main obj = new Main(); // calling the setter and the getter method obj.setName("Toshiba"); System.out.println("obj.name: "+obj.getName()); ) )

Uscita :

 obj.name: Toshiba

Qui abbiamo usato la thisparola chiave:

  • per assegnare un valore all'interno del metodo setter
  • per accedere al valore all'interno del metodo getter

Usandolo in Constructor Overloading

Mentre lavoriamo con il sovraccarico del costruttore, potremmo dover richiamare un costruttore da un altro costruttore. In tal caso, non possiamo chiamare esplicitamente il costruttore. Invece, dobbiamo usare la thisparola chiave.

Qui, usiamo una forma diversa di questa parola chiave. Cioè, this(). Facciamo un esempio,

 class Complex ( private int a, b; // constructor with 2 parameters private Complex( int i, int j )( this.a = i; this.b = j; ) // constructor with single parameter private Complex(int i)( // invokes the constructor with 2 parameters this(i, i); ) // constructor with no parameter private Complex()( // invokes the constructor with single parameter this(0); ) @Override public String toString()( return this.a + " + " + this.b + "i"; ) public static void main( String() args ) ( // creating object of Complex class // calls the constructor with 2 parameters Complex c1 = new Complex(2, 3); // calls the constructor with a single parameter Complex c2 = new Complex(3); // calls the constructor with no parameters Complex c3 = new Complex(); // print objects System.out.println(c1); System.out.println(c2); System.out.println(c3); ) )

Uscita :

 2 + 3i 3 + 3i 0 + 0i

Nell'esempio sopra, abbiamo utilizzato la thisparola chiave,

  • per chiamare il costruttore Complex(int i, int j)dal costruttoreComplex(int i)
  • per chiamare il costruttore Complex(int i)dal costruttoreComplex()

Notare la linea,

 System.out.println(c1);

Here, when we print the object c1, the object is converted into a string. In this process, the toString() is called. Since we override the toString() method inside our class, we get the output according to that method.

One of the huge advantages of this() is to reduce the amount of duplicate code. However, we should be always careful while using this().

This is because calling constructor from another constructor adds overhead and it is a slow process. Another huge advantage of using this() is to reduce the amount of duplicate code.

Note: Invoking one constructor from another constructor is called explicit constructor invocation.

Passing this as an Argument

We can use this keyword to pass the current object as an argument to a method. For example,

 class ThisExample ( // declare variables int x; int y; ThisExample(int x, int y) ( // assign values of variables inside constructor this.x = x; this.y = y; // value of x and y before calling add() System.out.println("Before passing this to addTwo() method:"); System.out.println("x = " + this.x + ", y = " + this.y); // call the add() method passing this as argument add(this); // value of x and y after calling add() System.out.println("After passing this to addTwo() method:"); System.out.println("x = " + this.x + ", y = " + this.y); ) void add(ThisExample o)( o.x += 2; o.y += 2; ) ) class Main ( public static void main( String() args ) ( ThisExample obj = new ThisExample(1, -2); ) )

Uscita :

 Prima di passare questo al metodo addTwo (): x = 1, y = -2 Dopo averlo passato al metodo addTwo (): x = 3, y = 0

Nell'esempio sopra, all'interno del costruttore ThisExample(), notare la linea,

 add(this);

Qui, stiamo chiamando il add()metodo passando questo come argomento. Poiché questa parola chiave contiene il riferimento all'oggetto obj della classe, possiamo modificare il valore di xey all'interno del add()metodo.

Articoli interessanti...