java - Is it ok to use 'this' in final instance variable declaration? -


is ok use this keyword in final instance variable declaration/initialization in java?

like this:

private final someclass foo = new someclass(this); 

it worked when tried out. , since not static variable guess should referring particular instance. felt unsure if advisable or not therefore wanted ask here.

edit: main class android activity class, , someclass-instance needs activity context.

it "technically valid" this. indeed, this refers particular instance - namely, instance contains instance of someclass.

but not recommend in general. exact behavior , state of this passed constructor depends on subtle details. consider 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";     }      string geta()     {         return a;     }     string getb()     {         return b;     }     string getc()     {         return c;     }     string getd()     {         return d;     }     someclass getref()     {         return ref;     } } 

i assume make neat job interview question, because predicting output hard. surprisingly, prints

state:     a: null    b: b    c: c    d: null  ref: null 

notice final variable c initialized, non-final variable d not intialized yet. in contrast that, non-final variable b (that declared before someclass instance) intitialized.

such subtelities questionable, , should avoided if possible.


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -