Java – Access methods from two interfaces’s implementation in a Class

designinheritancejavamultiple-inheritance

I am trying to implement the following pattern in a Cache layer.

I'm splitting the implementation of possible Cache methods such as getUsers() in UserCache Class, getLikes() in PostsCache class.

But I'd like all these methods to be accessible from a Single class object such as Cache.getUsers() , Cache.getLikes()

The reason behind this is, I'd like the developers who're using this layer to be unaware of the split that's been done behind this layer.

I've done the following

2 Interfaces – UserCache, PostsCache and
2 Classes implementing the interfaces – UserCacheImpl, PostsCacheImpl.

I tried to introduce a abstract class AbstractCache that implements these 2 interfaces and then this Cache class will extend that abstract class. But that failed 🙁

Now how can I combine these two be accessible from a single Cache object. Please guide me

Best Answer

It's perfectly possible for you to have

a[n] abstract class AbstractCache that implements these 2 interfaces and then this Cache class will extend that abstract class

public interface UserCache {
    int getUsers();
}

public interface PostsCache {
    int getLikes();
}

public abstract class AbstractCache implements UserCache, PostsCache {
    @Override public int getUsers() { return 12; }
    @Override public int getLikes() { return 34; }
}

public class Cache extends AbstractCache {
}

and that all compiles perfectly fine. What it is of course not possible to do in Java is to have multiple inheritance, where one class extends two classes (as opposed to implementing two interfaces), so you can't do

public abstract class AbstractCache extends UserCacheImpl, PostsCacheImpl {
}

and I suspect this is what you're actually trying to do. The solution here is to favour composition over inheritance:

public abstract class AbstractCache implements UserCache, PostsCache {
    private UserCacheImpl userCache;
    private PostsCacheImpl postsCache;

    public AbstractCache() {
        userCache = new UserCacheImpl();
        postsCache = new PostsCacheImpl();
    }

    @Override public int getUsers() { return userCache.getUsers(); }
    @Override public int getLikes() { return postsCache.getLikes(); }
}
Related Topic