Letting superclass's methods be implemented by an inherited class

Say I have this structure for my code:

public abstract class A{ 
    public abstract Foo methodX();
    public abstract Bar methodY();
}

public class B extends A {
    public Foo methodX(){
        // stuff
    }
    public Bar methodY(){
        // more stuff
    }
}

public class C extends A {
    public Foo methodX() {
        // stuff
    }
    public Bar methodY(){
        // What to do?
    }
}

public class D extends C {
    public Bar methodY() {
        // do stuff
    }
}

public class F extends C {
    public Bar methodY() {
        // do different stuff
    }
}

The reason for me to do this is because I have multiple classes extending A, all have common method methodX() and methodY() and I have multiple classes extending B all have some common properties to B but need to have different ways of doing methodY() and have different equals/hashcode.

So, how do I have it so that B implements the only methodX() but lets C and D implement methodY() without returning null or doing nothing in methodY() for B?

728x90

1 Answers Letting superclass's methods be implemented by an inherited class

You need to declare class B as abstract

public abstract class B extends A{
    public Foo medhodX(){
        // stuff
    }
}

By declaring class abstract you allow him not to implement all abstract methods (from superclass or implemented interface). So you can implement only one abstract method and force child class to impleent all remaining abstract methods.

2 year ago