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.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • bodytext
  • Technorati
  • Reddit
  • StumbleUpon
  • description
  • Wykop
  • Gwar
  • e-mail

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


  1. No Comments

Leave a Reply