oop
9. Covariant Return Types: Specificity
Analyze the code, write your predicted output, and then reveal the solution.
Scenario
Can an overriding method return a different type than the original? Yes, if it's a subclass of the original return type.
Code Block
class Food {} class Pizza extends Food {} class Restaurant { Food order() { return new Food(); } } class Pizzeria extends Restaurant { @Override Pizza order() { // Covariant return type (Pizza is a Food) return new Pizza(); } } public class Main { public static void main(String[] args) { Restaurant res = new Pizzeria(); Food f = res.order(); System.out.println("Ordered: " + f.getClass().getSimpleName()); } }
Take Your Shot
Predicted Output
Type exactly what you think will be printed in the console.