Java多态: How to indicate comparison should be made using subclass?

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

最佳答案

由于IntegerDouble都扩展了Number,然后将ArrayList重新定义为

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

然后

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

关于Java多态: How to indicate comparison should be made using subclass?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43927625/

相关文章:

delphi - 为什么 Delphi 变体不能保存对象?

Java 设计模式

java - 无法使用相对定位器单击第二个复选框

java - 我如何用 int 数组编写获胜方法

javascript - 通过实例方法使用 JS Classical

javascript - "[object Object]"中小写字母与大写字母所暗示的控制台区别

javascript - 使用 Vue3 对产品进行分组并显示产品数组中的数量

java - NoSuchBeanDefinitionException : No bean named 'name' is defined

Java : Displaying time in UTC

python - 什么是面向对象编程的计算开销成本?