I've seen code that have passed the keyword this as an input parameter.
For instance:
getContainer(this);
What does the keyword this mean? I've heard that it refers to an instance of the class itself (or something along those lines), but how does that work?
From 15.8.3 of the java specification:
The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs. When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed. The type of this is the class C within which the keyword this occurs. At run time, the class of the actual object referred to may be the class C or any subclass of C.
[...]
The keyword this is also used in a special explicit constructor invocation statement, which can appear at the beginning of a constructor body (§8.8.7).
So yeah, a class can use the this keyword to refer to itself. The this keyword is also required when a local variable within a method has the same name as a class member variable, to distinguish them both.
this can also be passed to pass the instance of the calling class to the called class.
for example
public class Caller{
public void callerClassMethod1(){
new Called(this).
}
public void callerClassMethod2(){
}
}
class Called{
private Caller caller;
public Called(Caller caller){
this.caller=caller;
}
public void calledClassMethod1(){
//.... Do something before
caller.callerClassMethod2();
//..... Do something after
}
}
This way you can separate the responsibilities of the 2 classes and at the same time keep them coupled.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With