简体   繁体   中英

Calling super class method inside implemented abstract method

Basicaly I have a need for several methods that do the same thing but with different parameters the sub-classes can chose from, and still force the implementation. Is this a correct approach/design ?

EDIT: I have edited the addItem() body, these methods contain the final logic that is used to handle the passed parameters

public abstract Class A {
    public abstract void addItemImpl()

    addItem(String s) {
        // do stuff
    }
    addItem(Collection c) {
       // do stuff
    }
    addItem(Item item) {
        // do stuff
    }
}

public  Class B extends A {
    addItemImpl() {
        addItem("text, text2")
    }
}

public Class C extends A {
    addItemImpl() {
        addItem([item, item2])
    }
}

No, this will not work.

You will not be able to define the "doStuff()" method because you have to handle the parameters. You provide not enough information to give you detailed help. But it's possible that generics might come in handy:

public abstract Class A<T> {
    public addItem(T t) {
        // dostuff with t
    }
}

public  Class B extends A<String> {
}

public Class C extends A<Collection> {
}

What you have is technically correct, but with out knowing what addItem actually does it is difficult to know if this is the best solution. My guess would be that there probably is a better way.

If addItem essentially set values to be used in the doStuff, I would just do that work in the Class B and C instead. Any others that need to do it the same way as B could extend it instead of A .

Edit: Based on your edit, I would say this is probably a bad example to use an abstract class. There is no truely shared functionality. An interface would be more appropriate as you need a different implementation for each. You are just trying to hide that inside an abstract class. I would change A to an interface along with using generics.

Only go the abstract class route if there is actually shared code that is exactly the same in all the classes without having to do any tricks to make it work (like above).

This is a perfect case for: Favor composition over inheritance.

Your subclasses don't fully benefit from the superclass and don't depend on its implementation details. Then define an interface for the contract B and C must obey ( addItemImpl() ) and compose them with A .

Ask yourself: is B really an A ? is C really and A ?

If you need force implementation for few methods, then Abstract methods are ideal.

But be careful only the very first Non-Abstract sub-class of the Super-class is bound to implement all the abstract methods in it....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM