【发布时间】:2017-06-03 16:07:18
【问题描述】:
各位程序员们好,
我现在正在处理一个 Java 项目,我正在尝试将一个已知的超类转换为一个未知的子类。
代码如下:
public void getShirtType(Person person) {
Clothing article; // Clothing is a superclass of different subclasses of Clothing
for(Clothing clothing : person.getClothing()) { // person.getClothing() returns List<Clothing>
if(clothing.hasSleeves()) { // hasSleeves() is boolean
article = ???;
break;
}
}
}
此代码获取 Clothing with sleeves 文章的第一个实例,然后结束循环。
我不知道在问号的位置放什么。通常,我可以有类似article = (SleevedShirt) clothing; 的东西,但是除了 SleevedShirt 之外还有各种不同的子类可以放在括号内。
让我知道你的想法。
另外,我主要是初学者,所以如果你愿意提供与我的代码相关的建设性批评,我不介意。
【问题讨论】:
-
article = clothing;怎么样,因为article也是一个类型Clothing?无需演员。 -
就这么简单?好的,我会试试的。谢谢。
标签: java class casting subclass superclass