【问题标题】:Casting(?) a known superclass object to an unknown subclass reference将已知的超类对象强制转换(?)到未知的子类引用
【发布时间】: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


【解决方案1】:

不需要演员(SleevedShirt) as

article = clothing;

应该足够了。

【讨论】:

  • 感谢您的信息。
猜你喜欢
  • 2013-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-23
  • 1970-01-01
  • 2013-01-15
  • 2013-09-03
相关资源
最近更新 更多