【问题标题】:Java polymorphism: How to indicate comparison should be made using subclass?Java多态性:如何指示应使用子类进行比较?
【发布时间】:2017-10-11 04:14:55
【问题描述】:

介绍性问题来了!以下代码...

public class HelloWorld
{
  public static void main(String[] args)
  {
    ArrayList<Object> A = new ArrayList<Object>();
    Integer I = new Integer(3);
    Double D = new Double(3.14);

    A.add(I);
    A.add(D);

    if (A.get(0) > 2)
    {
        System.out.print("Hello World");      
    }  
  }
}

...编译失败

bad operand types for binary operator '>'
        if (A.get(0) > 2)
                     ^
  first type:  Object
  second type: int

如何表明我希望与子类Integer 进行比较,而不是Object

【问题讨论】:

  • 投到Integer?
  • 由于你声明了ArrayList 持有类型Object,而&gt; 运算符不适用于Object,这是正常的。泛型是编译器关于类型的断言。如果您不断言支持您想要的操作的类型,那么这些操作将失败。

标签: java oop object polymorphism


【解决方案1】:

IntegerDouble 都扩展 Number 然后将 ArrayList 重新定义为

ArrayList<Number> A = new ArrayList<Number>();

然后

if (A.get(0).intValue () > 2)

【讨论】:

  • A.get(0).doubleValue () 更好。
猜你喜欢
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
相关资源
最近更新 更多