4. This

Visibilità

Le variabili locali di un metodo (o parametri formali) possono mascherare gli attributi della classe.

La soluzione al problema è l’utilizzo della pseudo-variabile this, che contiene il riferimento all’oggetto corrente.

Ex.

public class Car {
	private String color, brand, model;

	public void transform(String brand, String model){ 
		this.brand = brand;
		this.template = template;
	}

	public static void main(String[] args){
		Car a = new Car();
		a.transform("Ford", "T4"); 
	}
}

Ritornare un riferimento

La pseudo-variabile this può essere usata per ritornare un riferimento all’oggetto corrente.

Ex.

public class SetOfInters {
	public SetOfInters insert(int i) {
		// modify this by inserting the element i 
		return this; //returns the modified set
	}
}
SetOfInterest x,y,z;
//here x and y are initialized appropriately 
z = (x.insert(2)).union(y);
//useful that insert returns a set