Tom Elliott
Tom Elliott

Reputation: 1926

Is it ok to overload implementation of an interface?

I've recently had to break a simple class down into two versions, a Legacy version for older client versions, and a newer version that has migrated to a separate interface.

As there is much common code, I split this down into an abstract class with 2 concrete classes. With a structure as in the below:

interface ParentInt {
    // Common methods
}

interface ChildIntA extends ParentInt {
    // Legacy methods
}

interface ChildIntB extends ParentInt {
    // New model methods
}

abstract class AbstParentClass implements ParentInt {
    // ...
}

class LegacyConcreteClass extends AbstParentClass implements ChildIntA {
    // ...
}

class NewConcreteClass extends AbstParentClass implements ChildIntB {
    // ...
}

What I'm wondering is whether there are any pitfalls I might encounter because AbstParentClass implements ParentInt and the two concrete classes also implement children of this interface? Might there be a better pattern for this situation?

My code currently all works regardless of whether AbstParentClass has this implements directive or not. In fact, because the two concrete classes are instantiated separately in different threads, AbstParentClass is never actually referenced directly anywhere else.

In my situation the interfaces are part of an API and as such are unchangeable from my POV.

Upvotes: 0

Views: 134

Answers (2)

Dave Newton
Dave Newton

Reputation: 160251

There's no technical problems. Whether it makes sense in your application is a separate issue, but we don't know enough to answer that.

The other thing that may or may not be an issue is the new interface being tied specifically to the legacy interface. If the legacy interface goes away, you'd need to either un-tie the two, or keep the cruft.

It might be easier to keep them separated by having the new class(es) implement two interfaces. Whether or not it makes sense to extend an abstract base class becomes a bit murkier then.

Upvotes: 2

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81704

There are no problems with this approach. I understand your concern about the apparent "multiple inheritance", but the way that Java handles interfaces ensures that this kind of thing is never actually an issue. Interface methods with the same signature are "fused" and only one implementation method is allowed or required, regardless of how many identical interface methods are inherited.

Upvotes: 1

Related Questions