1
interface A {
    void someMethod();
}

class B implements A {
    void someMethod() {
        //do something
    }
}

class C extends B implements A {
    void someMethod() {
        super.someMethod();
        //do something
    }
}

I'm using the above design in one of my codes. It is working fine. My whole purpose here is to use the default implementation of class B and do something extra in class C. Is this the correct way to use the implementation? Is there any better design patter to be looked at?

Because If I define my class C as below, still everything works fine. But this neglects the whole purpose of using implementation (to force class C to implement methods of interface A).

class C extends B implements A {}
Community
  • 1
  • 1
Utkarsh
  • 17
  • 3

3 Answers3

0

Yes, it's perfectly fine to both extend and implement on the same classes. in fact, if you'll look at HashMap (and many others), that's exactly what it does:

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable 
Nir Levy
  • 12,750
  • 3
  • 21
  • 38
  • 2
    It might be worth linking to the question explaining why the collections framework does both, e.g. https://stackoverflow.com/questions/18558536/why-does-arraylist-class-implement-list-as-well-as-extend-abstractlist – Andy Turner Jul 27 '20 at 13:33
0

It still works fine because when you extend B that comes along with an implementation of someMethod, thus fulfilling the contract.

J.D. Luke
  • 66
  • 4
0

Please understand that class C extends B implements A is exactly equal to class C extends B other than the quick documentation purpose.

Try removing the defination of someMethod() from class C and see if your code compiles or not. It will compile. The reason is, the moment you made C extend B, C by default gets all the methods defined in B which includes an impementation of someMethod() as well. Defying the whole purpose of your explicit contract.

If you really want to force C to give a defination of someMethod() then try the following code:

interface A {
    void someMethod();
}

abstract class B implements A {
    protected void someUtilMethod() {
        //do common/default defination
    }
}

class C extends B {
    void someMethod() {
        someUtilMethod();
        //do extra something
    }
}
Community
  • 1
  • 1
Sisir
  • 4,584
  • 4
  • 26
  • 37