Interfaces and abstract classes in Java: Given the interface below, which two class/interface fragments will compile? interface Base { boolean m1(); byte m2(short s); } Fragments: interface Base2 implements Base {} abstract class Class2 extends Base { public boolean m1(){ return true; } } abstract class Class2 implements Base {} abstract class Class2 implements Base { public boolean m1(){ return (7 > 4); } } abstract class Class2 implements Base { protected boolean m1(){ return (5 > 7); } }

Difficulty: Medium

Correct Answer: 3 and 4

Explanation:


Introduction / Context:
This question evaluates understanding of how classes implement interfaces, how interfaces extend other interfaces, and how abstract classes can omit implementations of interface methods.



Given Data / Assumptions:

  • Base declares two methods: m1() and m2(short).
  • We must determine which fragments are syntactically valid in Java.


Concept / Approach:
Key rules: (1) Interfaces extend interfaces; they do not implement them. (2) Classes implement interfaces (not extend) and must provide public implementations for interface methods unless the class is abstract. (3) An implementing method cannot reduce visibility.



Step-by-Step Solution:

Fragment 1: interface Base2 implements Base → invalid; interfaces must use extends.Fragment 2: abstract class ... extends Base → invalid; classes cannot extend an interface; also only one method provided.Fragment 3: abstract class ... implements Base with no bodies → valid; abstract class may defer implementation.Fragment 4: Provides a public body for m1() and can remain abstract because m2 is unimplemented → valid.Fragment 5: Uses protected for m1(); visibility is weaker than the interface's public contract → invalid.


Verification / Alternative check:
Compiling minimal classes with each fragment confirms that only 3 and 4 succeed.



Why Other Options Are Wrong:
They rely on incorrect keywords, inheritance relationships, or visibility modifiers.



Common Pitfalls:
Confusing extends vs. implements; forgetting that interface methods are implicitly public abstract.



Final Answer:
3 and 4

More Questions from Declarations and Access Control

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion