java - need to add only parent class objects in the list and restrict the sub class objects -


i need declare list should accept parent class objects , should not allow sub class objects.

parent class:  public class parentclass {    private string parentattr;    public string getparentattr() {     return parentattr;   }    public void setparentattr(string parentattr) {     this.parentattr = parentattr;   }  }   sub class:  public class subclass1 extends parentclass {    private string attr1;    public string getattr1() {     return attr1;   }    public void setattr1(string attr1) {     this.attr1 = attr1;   }  }  main class:  public class mainclass {    public static void main(string[] args) {     parentclass parentclass=new parentclass();      subclass1 subclass1 = new subclass1();      list<parentclass> list=new arraylist<parentclass>(); // modify declaration such should accept parent class objs      list.add(parentclass);      list.add(subclass1); // should not happen. parent class objects should added in list    }  } 

i tried using generics well. not working. there way achieve in java generics?

you can implement list interface , provide own implementation list.add(int index, e element) method , check if element instanceof parent class , not instanceof child class in implementation.

you can extend arraylist class , override methods add elements arraylist , check if element instanceof parent class , not instanceof child class in implementation , call super method process of adding element(s).


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -