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.
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();
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With