Java - Inheritance - Can you return a child self into parent instance method that returns self? -
this question has answer here:
i have own custom list has bunch of functionality since manipulating same kinds of lists wanted extend custom list defined type , want able use parent functions , return child type.
example:
//object within list public class childobject { private string name; // getters, setters, methods, etc. } // parent custom list public class parentlist<t> extends arraylist<t> { public parentlist<t> filter(predicate<t> predicate) { collector<t, ?, list<t>> collector = collectors.tolist(); list<t> temp = this.stream().filter(predicate).collect(collector); this.clear(); this.addall(temp); return this; } } // extended custom list predefined type public class childlist extends parentlist<childobject> { // other methods } // implementation public static void main(string[] args) { childobject = new childobject("alice"); childobject b = new childobject("bob"); childlist filterlist = new childlist(); filterlist.add(a); filterlist.add(b); filterlist.filter(c -> childobject.getname().equals("alice")); }
it nice if possible feel free chime in whether doable, practical, or have thoughts on performance issues or bad practices.
i did figure out solution want know if way make work without following solution:
// extended custom list predefined type public class childlist extends parentlist<childobject> { public childlist filter(predicate<childobject> predicate) { super.filter(predicate); return this; } // other methods }
Comments
Post a Comment