This question is a synthetic exercise to help you understand the situations where adding a default method to an interface can cause classes that implement that interface to fail to compile.
Take a look at the classes and interfaces under solutions/code/tutorialquestions/question17b1/beforedefault
.
There are three interfaces, I
, J
and K
.
Interface I
specifies two overloads of a foo
method, as well as a bar
method:
public interface I {
int foo();
int foo(int x);
int bar(int x);
}
Interface J
specifies the same single-argument foo
and bar
methods as I
(but no zero-argument foo
method):
public interface J {
int foo(int x);
int bar(int y);
}
Interface K
extends both I
and J
, and adds an additional specification for a zero-argument method, baz
:
public interface K extends I, J {
void baz();
}
This means that to implement K
, a class needs to provide methods with all of the following signatures:
int foo(); // Required by I
int foo(int x); // Required by I and J
int bar(int x); // Required by I and J
void baz(); // Required by K
Now take a look at classes A
, B
and C
.
Class A
implements I
, providing implementations of all the required methods, plus of two additional methods with the following signatures:
public int foobar();
public void foobar(int x);
Class B
implements both I
and J
, providing just those methods required by these interfaces.
Class C
implements K
, providing implementations of the methods required by I
and J
as well as the extra method required by K
. Additionally, C
provides two further methods with the following signatures:
public int foobar() throws IOException;
protected int foobar(int x);
Your task:
-
Add the following default methods to
I
:default int foobar() { return bar(foo()); } default int foobar(int x) { return bar(foo(x)); }
Add the following default method to
J
:default int foobar(int x) { return bar(foo(x)); }
Add the following default method to
K
:default int foobar(int x) { return I.super.foobar(x); }
-
You should find that the addition of these methods leads to several compilation problems in the implementing classes
A
,B
andC
, due to incompatible method signatures.For each such problem, deal with it in one of the following ways:
-
Add a method to the class that is failing to compile in order to resolve the clash. (In this case you can implement the method in any way that respects the method's signature; the details of what the method actually does are not important for this question.)
-
Rename a method in the class that is failing to compile by adding
Original
to the end of its name (so that e.g.foo
would becomefooOriginal
)
In each case, write a brief comment explaining why you added or renamed the method.
-