开发者

differentiate between each children classes in an arraylist of parent class

开发者 https://www.devze.com 2023-01-28 03:28 出处:网络
hi I have a parent class that is Abstract Employee and I have childrens Secretary, Engineer, 开发者_如何学CTechnician If i have ArrayList<Employee> employees; and in a for loop I have randomly m

hi I have a parent class that is Abstract Employee and I have childrens Secretary, Engineer, 开发者_如何学CTechnician If i have ArrayList<Employee> employees; and in a for loop I have randomly made employee=new Secretary or new Engineer...

Is there a way of knowing who's who ? apologies for my ignorance if the question wasn't well asked.


Ideally, you should not care. If you need to do different things depending on which specific class it is, then it should go into a (possibly abstract) method in Employee which the subclasses override and implement differently. Then you just go through the list and call that method on every element.

This would be proper object oriented design.


You can use instanceof native operator.

Something like this:

List<Employee> yourList;
for (Employee e : yourList) {
    if (e instanceof Secretary) {
        Secretary s = (Secretary)e;
        // do something with s
    } else if (e instanceof Engineer) {
        Engineer eng = (Engineer)e;
        // do something with eng
    }
    // you get the idea...
}

Having said that, abusing use of instanceof is not always a good idea. You will have a cleaner more object oriented solution by using polymorphism in your class.


I strongly recommend you to implement the visitor pattern in situations like these.

You may also want to look at a complete example over here which solves this precise problem in the context of a list of Animals extended by Lions and Deers.


You can certainly use instanceof, but it will defeat the purpose of your design. Every time you add another subtype of Employee you'll have to modify potentially lots of code - every place that operates on this list.

Another way to do it that could reduce the number of changes (or at least keep them in one manageable place) is to use a Visitor pattern or polymorphism to let code figure out what to do based on type at runtime.

0

精彩评论

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