1Z0-819 · Question #142
Given: public interface InterfaceOne { void printOne(); } Which three classes successfully override printOne()? (Choose three.)
The correct answer is A. public abstract class TestClass implements InterfaceOne { public abstract void printOne(); } C. public class TestClass implements InterfaceOne { public void printOne() { System.out.println("one"); } } D. public abstract class TestClass implements InterfaceOne { public void printOne() { System.out.println("one"); } }. A is valid because an abstract class is permitted to re-declare an interface method as abstract, deferring the implementation to its concrete subclasses - the contract is still honored at the class hierarchy level. C is the textbook correct override: same signature, public…
Question
Options
- Apublic abstract class TestClass implements InterfaceOne { public abstract void printOne(); }
- Bpublic class TestClass implements InterfaceOne { private void printOne() { System.out.println("one"); } }
- Cpublic class TestClass implements InterfaceOne { public void printOne() { System.out.println("one"); } }
- Dpublic abstract class TestClass implements InterfaceOne { public void printOne() { System.out.println("one"); } }
- Epublic abstract class TestClass implements InterfaceOne { public String printOne() { return "one"; } }
- Fpublic class TestClass { public void printOne() { System.out.println("one"); } }
How the community answered
(27 responses)- A70% (19)
- B19% (5)
- E4% (1)
- F7% (2)
Explanation
A is valid because an abstract class is permitted to re-declare an interface method as abstract, deferring the implementation to its concrete subclasses - the contract is still honored at the class hierarchy level. C is the textbook correct override: same signature, public visibility, concrete body in a concrete class. D works because an abstract class may provide a concrete implementation for an interface method; the abstract keyword on the class doesn't prevent it from implementing some or all interface methods.
B fails because overriding cannot reduce visibility - interface methods are implicitly public, so making the override private is illegal and won't compile. E fails because the return type changes from void to String; String is not a covariant subtype of void, so this is an invalid override that won't compile. F is a red herring: the class has a matching method but never declares implements InterfaceOne, so it doesn't override anything from the interface - it just happens to have a method with the same name.
Memory tip: Think of two rules - "you can't go narrower" (visibility must stay public or go wider, never private/package-private) and "abstract classes get a pass" (they can either re-declare abstract or provide the body, but concrete classes must provide the body). Any mismatch in return type is an instant compiler error.
Topics
Community Discussion
No community discussion yet for this question.