Java – multiple object types in an ArrayList

I have an abstract class named user, which can be created as student type or teacher type I have created an ArrayList of users (students and teachers). What I want to do is call a method example, depending on what 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 it is the ArrayList of the user object, and it cannot get student type methods, such as getgrade() However, because I can determine what the current user's instance is, I wonder if I can still call specific methods according to the user's type

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

Please reply as soon as possible. Thank you very much

Solution

Check downcast:

Change your code to:

if (user instanceof Student) {

    ((Student) user).getGrade();

  } else { // it is an instance of a Teacher

    ((Teacher) user).getSubject();
  }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>