OCP Stage 2 Problem 1.19 – Explanation

Given:

class JavaCert {
    protected Number getScore() {
        return 85;
    }
}

Which two return types are allowed for the methods that override getScore()?

A. int
B. double
C. Double
D. AtomicInteger

E. Object
F. String
G. Character

 

The correct answer is CD.

 

Java allows an overriding method to return a subtype of the original method’s return type. This is known as covariant return types. From here follows that any valid subtypes of the wrapper class Number are allowed in this scenario. These subtypes include the classes that were featured on our OCA exam, namely Byte, Short, Integer, Long, Float, and Double, plus – as far as the OCP exam is concerned – the AtomicInteger class that is defined in the java.util.concurrent.atomic package. Please note that Character does not extend Number; this class sits directly under Object.

EXTRA:
AtomicLong, BigInteger and BigDecimal (the last two classes are from java.math) are also descendants of Number but these classes are not on our exam.

 

Since getScore() returns a reference type, we can’t return an int or a double to override the original method, which eliminates options A and B. After all, primitive types are not valid subtypes of any wrapper class, including Number. Although boxing is performed automatically for primitive types and wrapper classes, return types for overridden methods do not support autoboxing:

class Father {
    /* more code  */
    public Integer getAge() {
        return 35;
    }
}

class Son extends Father{
    /* more code  */
    public int getAge() {      // INVALID
        return 10;
    }
}

As for option E, the return type Object is not allowed in our case since Object is Number‘s supertype rather than subtype.

Finally, the return type String in option F cannot be used to override getScore(), either. Just like Character, this datatype is not related to the Number class by inheritance.

 

Takeaway:
Overriding is possible only when the return types are covariant (in case of reference types) or exactly the same (in case of primitives). Covariant return types must be related by inheritance – except, obviously, when we define the very same type in the overriding method, too.

 

Objective:
Java Class Design

Sub-Objective:
Implement polymorphism

Leave Comment

Your email address will not be published.