Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple object types in one ArrayList

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

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'm having is because it is an ArrayList of User objects, it can't get the Student type method, for example, getGrade(). However, because I am able to determine what the current user is an instance of, I'm curious as to whether or not it is still possible to call a specific method depending on what type of user it is.

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

Please reply soon, many thanks.

like image 465
Kurtiss Avatar asked Apr 10 '14 13:04

Kurtiss


2 Answers

You'll need to cast them to the class before using the method.

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();
    }
}
like image 149
Patrick J Abare II Avatar answered Sep 21 '22 20:09

Patrick J Abare II


Check the downcast:

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

In many programming languages, it is possible to check through type introspection to determine whether the type of the referenced object is indeed the one being cast to or a derived type of it, and thus issue an error if it is not the case.

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

Change your code to:

if (user instanceof Student) {

    ((Student) user).getGrade();

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

    ((Teacher) user).getSubject();
  }
like image 41
user987339 Avatar answered Sep 22 '22 20:09

user987339