Search code examples
javaobjectcastingpolymorphismcompareto

Why is compareTo() receiving runtime error when comparing two objects?


When referencing the object "r2" at line 12, there is a runtime error. Why is this?

public static void main(String[] args) {
    
    Rational r1 = new Rational(-2, 6);
    System.out.println(r1.getNumerator());
    System.out.println(r1.getDenominator());
    System.out.println(r1.intValue());
    System.out.println(r1.doubleValue() + "\n");
    
    Object r2 = new Rational(1,45);
    System.out.println((r2).compareTo(r1));
    
}

In line 11, I changed the object class to Rational and the code works but it does not work with Object r2. I'm just curious as to the underlying reason this doesn't work with Object r2.


Solution

  • Object does not declare a method with the name compareTo, thus you cannot call it. Typically, classes that provide a sorting order implement Comparable, so this is the type you should use for just a guarantee of being able to compare two objects.