Assuming I have an array of User
objects where each object is actually 开发者_JAVA百科one of two classes that extends User
. ComputerUser
and HumanUser
both extend User
.
Assume I'm iterating through the list and each object is named o
when I am using it.
Can I figure out if o
is a ComputerUser
or HumanUser
simply by comparing like this:
if(o.getClass().equals(ComputerUser.class)) {}
else if(o.getClass().equals(HumanUser.class)) {}
if (o instanceof ComputerUser)
etc
You can use the instanceof operator :
if (o instanceof ComputerUser) {
...
}
though this is considered poor use of object oriented programming. An alternative is to leverage polymorphism and define the behavior appropriate to a ComputerUser vs a HumanUser as such :
abstract class User {
abstract public void work();
}
class ComputerUser extends User {
@Override
public void work() {
...
//specific to ComputerUser
}
}
class HumanUser extends User {
@Override
public void work() {
...
//specific to HumanUser
}
}
精彩评论