Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing "this" in java constructor

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".

like image 472
Bruno Mello Avatar asked Mar 10 '10 18:03

Bruno Mello


People also ask

Can we pass this in constructor in Java?

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 .

Can I pass this in constructor?

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.

Can you pass this as a parameter in Java?

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.

What is this () in Java?

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).


1 Answers

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).

like image 82
Joachim Sauer Avatar answered Oct 16 '22 23:10

Joachim Sauer