Java多态:如何指示比较应该使用子类?

时间:2017-05-12 00:35:30

标签: java oop object polymorphism

介绍问题传入!以下代码......

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进行比较?

1 个答案:

答案 0 :(得分:2)

由于aplicatie.hs:1:12: error: • Expected a constraint, but ‘[Int a]’ has kind ‘*’ • In the type signature: afisare :: [Int a] => [a] -> b aplicatie.hs:1:13: error: • Expecting one fewer argument to ‘Int’ Expected kind ‘* -> *’, but ‘Int’ has kind ‘*’ • In the type signature: afisare :: [Int a] => [a] -> b Integer都延伸Double,然后将ArrayList重新定义为

Number

然后

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