user3217644
user3217644

Reputation: 97

Is it possible for several classes to share an interface implementation?

I have a number of java classes that are already implemented. I would like to add some behavior to these classes; this behavior in some cases could be identical for all classes. It is also assumed that I can not create a super class since all the classes are already implemented.

The question I have is what options do I have in this regard.

Interface: Is it possible that for some interfaces I implement them once and have classes share the single implementation (since in some cases the implementation required would be identical for all classes). This would avoid manual duplication of code in all classes.

I thought about defining an abstract class and having the classes extend the abstract class; the problem is that the sublcasses would in this case would not be a meaningful extension of the abstract class since they do not form a meaningful hierarchy.

Thanks.

Upvotes: 1

Views: 644

Answers (2)

dhm
dhm

Reputation: 2358

You can use the "delegation" pattern. Define a new interface with a method (or methods) defining the behavior you want to add, and an implementation class for each variant of the behavior. Have each of your existing classes reference an instance of whichever implementation class it needs. The wikipedia page for "Delegation Pattern" has some good simple examples in Java and other languages: https://en.wikipedia.org/wiki/Delegation_pattern

Upvotes: 1

Eran
Eran

Reputation: 393936

If the implementation of the interface methods doesn't depend on members of the implementing classes, and you are using Java 8, you can give the interface's methods a default implementation.

Upvotes: 2

Related Questions