OCP Question 2, Explanation

Given the class definitions:

class Plant {
    public String brew(String msg) {
        return msg;
    }
}
class Coffee extends Plant {
    public String brew(String msg) {
        return msg.replace('a', 'e');
    }
 }
class Arabica extends Coffee {
    public String brew(String msg) {
       return msg.substring(2);
    }
}

And the code fragment of the main() method,

List<Plant> cup = new ArrayList<Plant>();
cup.add(new Plant());
cup.add(new Coffee());
cup.add(new Arabica());
for (Plant item : cup) {
    System.out.println(item.brew("Java"));
}

What is the result?

A. Java
Java
Java
B. Java
Jeve
va
C. Java
Jeve
ve
D. Compilation fails

The correct answer is option B.

There’s no reason for a comperr because the List is declared and populated properly, and the inherited classes override brew() without errors. The enchanced for behaves itself, too, as the running var item is of type Plant and can, therefore, effortlessly accept either of its narrower subtypes.

The only place of concern is, perhaps, the replace() method: what if it replaces just the first instance of its target? Fortunately, we aren’t given an option that contains “Jeva” 🙂 ► a single-arg substring() simply chops off and discards whatever sits to the left of its arg.

Leave Comment

Your email address will not be published. Required fields are marked *