"This is technically fair." Indeed, this refers to a specific instance, namely the instance that contains the SomeClass instance.
But I would not recommend doing this in general. The exact behavior and state of this passed to the constructor depends on the subtle details. Consider the following example:
class SomeClass { public SomeClass(DangerousSelfReference dangerousSelfReference) { System.out.println("State: "); System.out.println(" a: "+dangerousSelfReference.getA()); System.out.println(" b: "+dangerousSelfReference.getB()); System.out.println(" c: "+dangerousSelfReference.getC()); System.out.println(" d: "+dangerousSelfReference.getD()); System.out.println(" ref: "+dangerousSelfReference.getRef()); } } public class DangerousSelfReference { public static void main(String[] args) { DangerousSelfReference d = new DangerousSelfReference(); } private String a; private String b = "b"; private final SomeClass ref = new SomeClass(this); private final String c = "c"; private String d = "d"; DangerousSelfReference() { a = "a"; } String getA() { return a; } String getB() { return b; } String getC() { return c; } String getD() { return d; } SomeClass getRef() { return ref; } }
I suppose this might make a tidy question about a job interview because itβs difficult to predict a way out. Amazing he prints
State: a: null b: b c: c d: null ref: null
Note that the final c variable is initialized, but not the final variable d has not yet been specified. In contrast, the non-final variable b (declared before the SomeClass instance) is already initialized.
Such subelements are always doubtful and should be avoided if possible.
Marco13
source share