I have an abstract Person
class which has 3 children: Admin
, Employee
and Student
. There is only one admin object.
I also have a class which it's "name" is Statics
and holds all public data I need, like this:
public class Statics {
private static Person currentLoginUser;
private static ArrayList<Person> people = new ArrayList<>();
private static ArrayList<Student> students = new ArrayList<>();
private static ArrayList<Employee> employees = new ArrayList<>();
//We don't need ArrayList<Admin> because there is only one admin in the whole program
//Adder and getter methods:
//...
}
You may ask what ArrayList<Person>
in the code is? When I create an object, I add it to both "it's own type arraylist" and "ArrayList<Person>
". So ArrayList<Person>
has everybody.
As I said, I only have 1 admin:
Person admin = new Admin(); //`Admin` extends `Person`
I want to create a method (in Admin
class) which takes an arrayList of Person
as input and prints it's data. So I did this:
//Admin class:
public void printList(ArrayList<Person> people){
//Do something
}
Let's assume admin
wants to see the list of the students: I call it like this:
ArrayList<Student> s = Statics.getStudents();
((Admin)admin).printList(s); //admin object was created by `Person` class so I have to cast it to (Admin) to use `Admin`'s own methods.
It (eclipse) says that:
The method printList(ArrayList<
Person
>) in the type Admin is not applicable for the arguments (ArrayList<Student
>)
I tried to cast it to person:
((Admin)admin).printList((ArrayList<Person>)s);
this time I got this error:
Cannot cast from ArrayList<
Student
> to ArrayList<Person
>
In this link the answer is to pass the main arrayList and check if it's object's are from type "Student" or not, then print it's value but I don't want to check the whole Person
arrayList everytime! I just want a method, which takes and arrayList of Person
's children (Employee
, Student
, etc) and prints them.