java - Multiple object types in one ArrayList -


i have abstract class called user, user can created either student type or teacher type. have made arraylist of users (of students , teachers) , trying call method example depending on current object instance of:

for (user user : listofusers) {    string name = user.getname();    if (user instanceof student) {      // call getgrade();    } else { // instance of teacher      // call getsubject();   } } 

the problem i'm having because arraylist of user objects, can't student type method, example, getgrade(). however, because able determine current user instance of, i'm curious whether or not still possible call specific method depending on type of user is.

is possible, or have separate user types separate lists?

please reply soon, many thanks.

check downcast:

in object-oriented programming, downcasting or type refinement act of casting reference of base class 1 of derived classes.

in many programming languages, possible check through type introspection determine whether type of referenced object indeed 1 being cast or derived type of it, , issue error if not case.

in other words, when variable of base class (parent class) has value of derived class (child class), downcasting possible.

change code to:

if (user instanceof student) {      ((student) user).getgrade();    } else { // instance of teacher      ((teacher) user).getsubject();   } 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -