Multiple Object Types in One ArrayList

I have an abstract User class, a user can be created either as a Student type or as a Teacher type. I made an ArrayList of users (students and teachers), and what I'm trying to do is to call an example method depending on who the current object is:

for (User user : listOfUsers) { String name = user.getName(); if (user instanceof Student) { // call getGrade(); } else { // it is an instance of a Teacher // call getSubject(); } } 

The problem I encountered is that these are ArrayList User objects, it cannot get a method like Student, like getGrade (). However, since I can determine who the current user is, I am curious if a particular method can still be called depending on what type of user it is.

Is this possible, or do I need to separate user types into separate lists?

Answer soon, thank you very much.

+6
source share
3 answers

Check downcast :

In object-oriented programming, a down-conversion or refinement of the type of act of casting a base class reference to one of its derived classes.

In many programming languages, you can check the type of introspection to determine if the type of the reference object is actually the one casted or derived from it, and, therefore, throw an error if it is not.

In other words, when a variable of a base class (parent class) has the value of a derived class (child class), a downgrade is possible.

Change your code to:

 if (user instanceof Student) { ((Student) user).getGrade(); } else { // it is an instance of a Teacher ((Teacher) user).getSubject(); } 
+4
source

Before using this method, you need to pass them to the class.

 for (User user : listOfUsers) { String name = user.getName(); if (user instanceof Student) { Student tmp = (Student)user; // call getGrade(); tmp.getGrade(); } else { // it is an instance of a Teacher Teacher tmp = (Teacher)user; // call getSubject(); tmp.getSubject(); } } 
+5
source

Store student and teacher objects in userList, and then, depending on the instanceOf condition, call the corresponding class method with the typeCasting method in UserType

Consider the code example below.

  abstract class User{ public abstract String getName(); } class Student extends User{ @Override public String getName() { // TODO Auto-generated method stub return "Student"; } public String getGrade(){ return "First Class"; } } class Teacher extends User{ @Override public String getName() { // TODO Auto-generated method stub return "Teacher"; } public String getSubject(){ return "Java"; } } public class Util { public static void main(String[] args) { Student s = new Student(); Teacher t = new Teacher(); ArrayList<User> list = new ArrayList<User>(); list.add(s); list.add(t); for(User user :list){ if(user instanceof Student){ System.out.println(((Student) user).getGrade()); } if(user instanceof Teacher){ System.out.println(((Teacher) user).getSubject()); } } } } 
+1
source

All Articles