Question

I am creating a small project that implements an interface in Java. I am not allowed to modify the interface, which means I can't change the functions in my class that implements the interface.

However, one of the methods in the class (from the interface) requires a different behaviour in some cases. How do I implement this, in a way that it allows me to adapt the behaviour and make changes to the method without changing the interface?

Was it helpful?

Solution

Your question is very general. So will be my answer.

The easiest way would be to write the implemented method to cover the special cases. It it's complex, you may delegate the execution to more specialised function (that can be outside the interface). But if it were that simple you wouldn't probably ask.

Another way could be :

  • to implement your method using a strategy. This allows you to handle special cases by changing strategy dynamically or by injecting it into the constructor.
  • to implement your class according to the state pattern. This is especially suitable if the "special cases" could apply to all the objects of your class, depending dynamically on the state of the object.

If the special conditions are related to special kind of objects (an not all objects), and if you are allowed to subclasses your implementing class, you may also consider:

  • to simply subclass your class and implement the method differently.
  • to implement your method as a template method, doing its job following a skeleton but using some private methods that could be specialized through inheritance.

As you see, there are plenty of ways of doing it. If you would provide more information, we could advise more specifically.

OTHER TIPS

The method that implements the interface will do exactly what the code that you put into the method does. So if you want the instances of your class to do something different when the interface method is called, you just do it.

Some interface methods are explicitely defined to work that way. For example, in iOS a UIViewController has an interface method viewWillAppear: which gets called just before a view controlled by the view controller appears on the screen, and the contract says that you as the developer take whatever actions you think are appropriate to take at that time.

Other interface methods tell you exactly what you should do (apart from the implementation of that interface depending on the details of the class in question). In that situation, if your implementation does something different, that will be unexpected and your application may misbehave.

Licensed under: CC-BY-SA with attribution
scroll top