Reputation: 37
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
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
Reputation: 1719
List<? extends Parent> listValue = new ArrayList<>();
if (listValue.get(1) instanceof Child)
{
Child child = (Child) listValue.get(1);
String value = child.childOnly;
}
Upvotes: 3