Reputation: 17
Can an interface have partially implemented methods? This is a question which asked from me in an exam. I don't have a clear idea on "partially implemented". Is it mean that methods of that interface has some operations? But normally we are having only the methods without body in the interfaces. So if anyone can answer me I would be more thankful.
Upvotes: 1
Views: 893
Reputation: 3818
The only way I can interpret this question so as to have a "yes" answer is to implement the "partial" part of the method as a default method and then to explicitly call the default method from the method which overrides it:
public interface Swallow {
default double getMaxAirspeed() {
// Partial implementation of the method to be called by its full implementation, which should override this default method
return 1.0;
}
}
public class AfricanSwallow implements Swallow {
public double getMaxAirspeed() {
final double initialValue = Swallow.super.getMaxAirspeed();
return initialValue * 2;
}
}
Upvotes: 0
Reputation: 48434
The only way an interface
can have "partially" implemented methods is through Java 8's default
methods:
// will compile in Java 8 only
interface Foo {
default void foo() {
System.out.println("Default foo implementation");
}
}
The standard way before Java 8 (and still valid conceptually depending on your scope) is to have a[n abstract] class providing a method with default behavior for its children.
Upvotes: 3