oop - Why can't I create a object in a function in Java? -


code works well, think code b can work correctly, in fact, code b doesn't work correctly. why?

why can't create object in function- private void setfield(context mcontext,matt afield,string name) ?

code a

public class murlpar {      public matt diskcount=new  matt();     public matt diskindex=new  matt();       public murlpar(context mcontext){         setfield(mcontext,diskcount,"pardiskcount");         setfield(mcontext,diskindex,"pardiskindex");     }       public class matt {         public string name;         public string value;     }       private void setfield(context mcontext,matt afield,string name){         int id = mcontext.getresources().getidentifier(name, "string", mcontext.getpackagename());         afield.name=mcontext.getstring(id);     } } 

code b

public class murlpar {      public matt diskcount;      public matt diskindex;       public murlpar(context mcontext){         setfield(mcontext,diskcount,"pardiskcount");         setfield(mcontext,diskindex,"pardiskindex");     }       public class matt {         public string name;         public string value;     }       private void setfield(context mcontext,matt afield,string name){         afield=new matt(); //create object         int id = mcontext.getresources().getidentifier(name, "string", mcontext.getpackagename());         afield.name=mcontext.getstring(id);     } } 

what's happening in code b murlpar constructor passes reference diskcount/diskindex setfield, within method has name afield.

you reassign afield reference newly created object, , manipulate object. note afield referring separate object, , not whatever referring when entered setfield.

if you're familiar c can think of you're doing here along these lines:

void setfield(matt *afield) {     afield = (matt*) calloc(1, sizeof(matt)); }  matt *diskcount; setfield(diskcount); 

and expecting diskcount have changed after call setfield, won't have.


if want out parameter, can simulate returning newly created object:

private matt setfield(context mcontext, string name){     matt afield = new matt(); //create object     int id = mcontext.getresources().getidentifier(name, "string", mcontext.getpackagename());     afield.name=mcontext.getstring(id);     return afield; } 

and then:

diskcount = setfield(mcontext, "pardiskcount"); 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -