I would like an explanation with an example if possible, about the reserved word this
in Java, I did not quite understand it.
I would like an explanation with an example if possible, about the reserved word this
in Java, I did not quite understand it.
this
refers to the current object. Always read this as it will become clear to you: this object
Example:
public class Esse {
public static void main(String[] args) {
Esse esse1 = new Esse();
Esse esse2 = new Esse();
esse1.compara(esse2);
}
public void compara(Object aquele) {
if(this == aquele) {
System.out.println("mesmo objeto");
}
else {
System.out.println("Objetos diferentes");
}
}
}
Result:
Different objects
In the main () method, when calling the compare () method, the object that called it is implicitly passed, in this case the object esse1
, then the comparison inside the method returned false, since esse1 != esse2
Including, this is the great difference of methods and functions, because when it is called a method its object is passed implicitly with it, and the same does not happen with functions in other languages, for example Pascal.
I said "wont say" because it is what some people argue (including me), but despite everything in Java being method and never functions, there are static methods that do not have an object attached to it, because methods static objects belong to the class and not to the object, so there is no need for an object created for them to be accessed.
Example:
public static void teste() {
System.out.println(this); //ERRADO!!
}
The code above is invalid because the method does not belong to the object, but to the class, so the object this
is not passed to the method that was called.
this
is also very commonly used to make explicit what variable we are talking about, whether it is the object variable or whether it is a local variable. Example:
public class Exemplo {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Notice the this.id = id
line, it is assigning the value of the local variable to the value of the object variable that was called the set method. If it were not possible to use this
the variables should have different names for the code to work correctly.