Extending Interfaces

Just as a subclass can extend a superclass via reserved word extends, you can use this reserved word to have a subinterface extend a superinterface. This is known as interface inheritance.

For example, the duplicate color constants in Drawable and Fillable lead to name collisions when you specify their names by themselves in an implementing class. To avoid these name collisions, prefix a name with its interface name and the member access operator, or place these constants in their own interface, and have Drawable and Fillable extend this interface, as demonstrated in Listing 3-36.

Listing 3-36. Extending the Colors interface interface Colors

int RED = 1; int GREEN = 2; int BLUE = 3; int BLACK = 4;

interface Drawable extends Colors

void draw(int color);

interface Fillable extends Colors

void fill(int color);

The fact that Drawable and Fillable each inherit constants from Colors is not a problem for the compiler. There is only a single copy of these constants (in Colors) and no possibility of a name collision, and so the compiler is satisfied.

If a class can implement multiple interfaces by declaring a comma-separated list of interface names after implements, it seems that an interface should be able to extend multiple interfaces in a similar way. This feature is demonstrated in Listing 3-37.

Listing 3-37. Extending a pair of interfaces interface A {

interface B {

interface C extends A, B

Listing 3-37 will compile even though C inherits two same-named constants X with different return types and initializers. However, if you implement C and then try to access X, as in Listing 3-38, you will run into a name collision.

Listing 3-38. Discovering a name collision class D implements C {

public void output() {

System.out.println(X); // Which X is accessed?

Suppose you introduce a void foo(); method header declaration into interface A, and an int foo(); method header declaration into interface B. This time, the compiler will report an error when you attempt to compile the modified Listing 3-37.

Was this article helpful?

0 0

Post a comment