Monday, 15 February 2010

java - Instancaite an instance of the child class from the parent -



java - Instancaite an instance of the child class from the parent -

first of, sorry vague title cannot think how word this, please edit in improve title if think of one.

i have helper fragment class (masterfragment), never used it, extended, , in there method.

public static masterfragment newinstance(bundle bundle) { masterfragment masterfragment = new masterfragment(); masterfragment.setarguments(bundle); homecoming masterfragment; }

when extend this, lets phone call class extendedmasterfragment, can create newinstance method homecoming instance of extendedmasterfragment instead of masterfragment?

edit: work around have this.

public static masterfragment newinstance(bundle bundle, masterfragment masterfragment) { masterfragment.setarguments(bundle); homecoming masterfragment; }

and called like

return listexamplefragment.newinstance(null, new listexamplefragment());

but i'd rather have newinstance work out class if possible

you, absolutely, can have newinstance method homecoming instances of subclasses:

public enum type { this, that, other; } public static masterfragment newinstance(bundle bundle, type type) { masterfragment frag; switch (type) { case this: frag = new thisfrag(); break; // ... } frag.setarguments(bundle); homecoming frag; }

on other hand, homecoming type of mill method masterfragment. have cast (ewwwieee) if need actual type of instance.

you can this, though really, ugly:

public static <t extends masterfragment> t newinstance(bundle bundle, type type) { masterfragment frag; switch (type) { case this: frag = new thisfrag(); break; // ... } frag.setarguments(bundle); homecoming (t) frag; // type conversion warning here. }

if utilize generics, work:

thisfrag frag = newinstance(new bundle(), type.this);

yuk. sorry mentioned it.

java android

No comments:

Post a Comment