When i try to create an instance of a class and add this to my arraylist i can’t call methods defined in the child.
How do i make this work?
List class:
import java.util.*;
public class List {
private ArrayList<Person> persons;
public List(){
persons = new ArrayList<Person>();
}
public void addAssistant(){
Person person = new Assistant();
persons.add(person);
if(person instanceof Assistant){
person.assist();
}
}
}
Person class:
public class Person {
public Person(){}
}
Assistant class:
public class Assistant extends Person {
public Assistant(){}
public void assist(){
System.out.println("I am assisting!");
}
}
Compiler:
line: person.assist(); within the addAssistant() method in the List class.
Compiler error:
The compiler cannot find symbol – method assist().
You need an explicit cast:
However, I think this type of logic should generally be discouraged.