java - Filling a generic List with objects of a subclass of an abstract class -
let's have abstract class called figure , static method addfigure inside. addfigure should fill existing list objects of user-specified type.
public abstract class abstractfigure { public static <t extends abstractfigure> void addfigure(list<t> list, class<t> clazz, int n) { (int = 0; < n; i++) { try { t obj = clazz.newinstance(); list.add(obj); } catch (instantiationexception ex) { ex.printstacktrace(); } catch (illegalaccessexception ex) { ex.printstacktrace(); } } } } then have subclass, square.
public class square extends abstractfigure { } the invocation follows:
public class genericsproblem{ public static void main(string[] args) { arraylist<square> arraylistsquare = new arraylist<>(); abstractfigure.addfigure(arraylistsquare, square.class, 12); } } the code works correctly , list filled squares, assume.
now, i'd re-make abstractfigure instead of working on existing list, it'll create , return one, in:
public abstract class abstractfigure { public static <t extends abstractfigure> list<t> addfigure(class<t> clazz, int n) { list<t> genlist = new arraylist<>(); (int = 0; < n; i++) { try { t obj = clazz.newinstance(); genlist.add(obj); } catch (instantiationexception ex) { ex.printstacktrace(); } catch (illegalaccessexception ex) { ex.printstacktrace(); } } return genlist; } } is possible , if so, how invoke it?
yes, possible. need assign return value variable.
list<square> arraylistsquare = addfigure(square.class, 12);
Comments
Post a Comment