I've spent a while thinking about different solutions that the one I went for as I've read around (I am not really experienced with Java yet) that using this for a constructor argument isn't usually a good practice.
What I am trying to do is to instantiate several objects of class JobGroupMod and for every JobGroupMod I have to create a certain number of JobMod objects that must be able to reference back the JobGroupMod objects in which they've been spawned from.
In order to accomplish that I am passing "this" to the JobMod constructor but, even if working, it didn't feel like proper designing.
public class JobGroupMod implements JobGroup {
public JobGroupMod(Node n,Set<Job> clusterJobs){
JobMod j=new JobMod(n,this);
}
}
And now the JobMod class:
public class JobMod implements Job {
public JobMod(Node n, JobGroup jg){
setJobGroup(jg);
}
}
My question is, is there a better way of solving this, or is my solution the suggested way?
'this' means 'current object'. In static methods there is no current object. In your example, try replacing this with new Main() .
The only way to "stop" a constructor is to throw an exception.
When passing an argument by reference, the method gets a reference to the object. A reference to an object is the address of the object in memory. Now, the local variable within the method is referring to the same memory location as the variable within the caller.
Definition and Usage 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). If you omit the keyword in the example above, the output would be "0" instead of "5".
You should try using a static factory method (Effective Java link).
This way you avoid passing this
in a constructor call, which is highly ill-advised to say the least.
example code:
public class JobGroupMod implements JobGroup {
public static JobGroupMod createModeMod(Node n, Set<Job> clusterJobs) {
JobGroup jg = new JobGroupMod();
JobMod j = new JobMod(n, jg);
return jg;
}
}
As long as it remains the only thing you do in the JobGroupMod
constructor is is fairly safe as long as you understand the ramifications. There's a lot of Java code in the real world that does this. It's still not something you really want to do, especially when you start talking about multithreading and concurrency.
The danger is passing this
to something else before an object is fully constructed. If the constructor were to throw an exception after you did this and not fully construct, you could have a nasty problem. If another thread were to access the object you passed this
to before it was fully constructed, you'd have a nasty problem.
What you'll often find in Java is people using a factory pattern to avoid this, an "init" type method, or dependency injection.
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