开发者

Which of the extension classes is this object?

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
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜