It is necessary to add only the objects of the parent class to the list and limit the objects of the subclass

I need to declare a list that should only accept parent class objects and it should not accept subclass 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 this declaration such that it should accept only the parent class objs

    list.add(parentClass);

    list.add(subClass1); // this should not happen. only parent class objects should be added in the list

  }

}

      

I have also tried using generics. But it doesn't work. is there a way to achieve this in Java generics?

+3


source to share


2 answers


You can implement the List interface and provide your own implementation for List.add (int index, E element) and check if this element is an instance of the parent class and not an instance of the child class in your implementation.



You can also extend ArrayList Class and override all methods that add elements to ArrayList and check if this element is an instance of the parent class and not an instance of the child class in your implementation and call the Super method for the process of adding element (s).

+1


source


Not. You just can't stop it. We can use every child as a parent. Each child extends to a parent and appears to be a Parent as well.



0


source







All Articles