开发者

Which of the extension classes is this object?

开发者 https://www.devze.com 2023-03-07 12:35 出处:网络
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.

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

精彩评论

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