检查子类的属性 [英] Check attribute of a subclass
问题描述
我偶然发现了这种情况,但我不知道如何以正确的方式处理它:
I stumbled across that situation but I don't know how to handle it the right way:
class Myclass { }
class MyclassWithAwesomeStuff extends Myclass {
public boolean awesomeStuff;
}
我将Myclass对象保存在数组列表中,然后通过此列表进行迭代:
I'm saving the Myclass objects in an arraylist and iterate later through this list:
for(Myclass m : list) {
//here I want to check if awesomeStuff is true, in case it is a MyclasswithAwesomeStuff
}
这里的问题是:父类Myclass doesn' t知道awesomeStuff属性(它不应该,因为这是一个功能,只有与派生类)。但我该如何管理呢?问题是,数组列表包含Myclass和MyclassWithAwesomeStuff元素,foreach循环将它们总是转换为Myclass。
The problem here is: the parent class Myclass doesn't know the awesomeStuff attribute (and it shouldn't because that is a feature that comes only with the derived class). But how can I manage this? The problem is, that the arraylist contains Myclass and MyclassWithAwesomeStuff elements and the foreach loop casts them always to Myclass.
我想知道这是否是设计失败?
I wonder if this is a design failure?
//编辑:
好吧,为了让我的问题更有形,这里有更多的信息。我试图建立一个小咖啡店:
Okay, to make my question a little bit more tangible, here more infos. I'm trying to build a small coffee shop:
class Coffee { }
class CoffeeMix extends Coffee {
public boolean shaken;
}
我将数组列表中的咖啡项目保存:
I'm saving the coffee items in an array list:
ArrayList<Coffee> coffees = new ArrayList<Coffee>();
因此在这个数组列表中存在普通的咖啡对象和咖啡混合对象。现在我想显示所有的咖啡混合对象,摇动:
So in this array list exist normal coffee objects and coffee mix objects. Now I want to display all coffee mix objects, that are shaken:
for(Coffee c : coffees) {
//here is the same problem as above
}
/评论:instanceof似乎是一个坏主意,因为它螺丝的想法背后oo和一个接口,两个类实现是一个坏主意,因为一个正常的咖啡不能动摇。那么如何处理呢?
As I can see from the answers/comments: instanceof seems to be a bad idea, because it screws the idea behind oo up and an interface that both classes implement is a bad idea too, because a normal coffee can not be shaken. So how to handle this?
推荐答案
测试 m
code> 运算符
Test if m
is a MyclassWithAwesomeStuff
with the instanceof
operator.
if (m instanceof MyclassWithAwesomeStuff)
{
MyclassWithAwesomeStuff mwas = (MyclassWithAwesomeStuff) m;
// Now you can access "awesomeStuff" with "mwas"
}
这篇关于检查子类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!