Prins Alvino
Prins Alvino

Reputation: 37

Accessing child property inside an array list of base class

I am trying to access the property of the child class inside an array list of the base class

ArrayList<Parent> listValue = new ArrayList<Parent>();
listValue.add(new Child1());
listValue.add(new Child2());

This is the class parent

class Parent{
String name;
public Parent(String name){
  this.name = name
  }
}

This is the child class

class Child extends Parent{
String childOnly;

public Child(String name){
super(name);
 }
}

And i am trying to access the class property somehow like this

string value = listValue.get(1).childOnly       

Upvotes: 1

Views: 1232

Answers (2)

Trần Ho&#224;n
Trần Ho&#224;n

Reputation: 94

you can check and cast:

Parent obj = listValue.get(1);
if(obj instanceof Child)
{
    chld Child = (Child)obj;
    string value = chld.childOnly;
...

Upvotes: 2

Pedro Borges
Pedro Borges

Reputation: 1719

  1. Specify that your list contains any subclass of Parent, like this:
List<? extends Parent> listValue = new ArrayList<>();
  1. Cast you object when fetching from the list, like this:
if (listValue.get(1) instanceof Child)
{
    Child child = (Child) listValue.get(1);
    String value = child.childOnly;
}

Upvotes: 3

Related Questions