What if you extend an abstract class and implement an interface when both define a method with the same name?

Imagine you need to implement a class that extends an abstract class and implements an interface when both define a method with the same name – test().

Example

interface Implementable { public void test(); }
abstract class Superclass { public abstract void test(); }

public class Test extends Superclass implements Implementable {
    /* definition of load method(s)..... */
}

The following will not compile, getting (among others) duplicate method test() error:

interface Implementable { public void test(); }
abstract class Superclass { public abstract void test(); }

public class Test extends Superclass implements Implementable {
    public void Superclass.test() { }
    public void Implementable.test() { }
}

Solution

The correct implementation looks as follows:

interface Implementable { public void test(); }
abstract class Superclass { public abstract void test(); }

public class Test extends Superclass implements Implementable {
    public void test() { }
}

In such case, you need to define the body of test() method ONLY ONCE.

Previous Post
Next Post