OCP Question 20, Explanation

Given:

class WhiteStarLiner implements Sinkable {
    public void sink() { }
}

abstract class Shipwreck extends WhiteStarLiner { }

class Britannic extends WhiteStarLiner {
    protected void sink(int numberOfMines) { }
}

class Titanic extends WhiteStarLiner implements Sinkable {
    public void hitIceberg() { }
}

interface Sinkable {
    public abstract void sink();
}

Which statement is true?

A. Shipwreck does not compile.
B. Britannic does not compile.
C. Titanic does not compile.
D. Sinkable does not compile.
E. All classes compile successfully.

 

The correct answer is E.

Marking the sink() method in Sinkable as public and abstract is redundant but not illegal. Since Shipwreck is abstract, it wouldn’t have to implement sink() even if concrete WhiteStarLiner hadn’t taken care of the method by overriding it correctly (note the public access modifier). The concrete Titanic is okay, too, because it inherited zero abstract methods, and, finally, Britannic is almost a twin to Titanic except it defines an overloaded-for-int sink(). If this sink() weren’t overloaded, its protected modifier would have flagged a comperr in Britannic.

Leave Comment

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