Look into the following code:
public class ClassA {
private boolean ClassAattr = false;
public ClassA() {
ClassAHandler handler = new ClassAHandler(this);
}
}
public class ClassAHandler extends GeneralHandler {
ClassA ca = null;
public ClassAHandler(ClassA classa) {
this.ca = classa;
}
}
I need to access ClassAattr
on some ClassAHandler
methods, among other attributes. Is there a way to do so without passing the origin class in the handler constructor. I don't really like how this solution "looks".
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .
You can pass an argument of any data type into a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as classes and arrays.
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.
The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
Passing this
to another method/object from inside the constructor can be rather dangerous. Many guarantees that objects usually fulfill are not necessarily true, when they are looked at from inside the constructor.
For example if your class has a final
(non-static
) field, then you can usually depend on it being set to a value and never changing.
When the object you look at is currently executing its constructor, then that guarantee no longer holds true.
As an alternative you could delay the construction of the ClassAHandler
object until it is first needed (for example by doing lazy initialization in the getter of that property).
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