Inconvenient OOP: The same method on different classes is not inherited?

Here's the deal: I have two objects of different classes: DataSizeAction and DataColorAction . Classes have a common ancestor EncoderAction not far from the chain.

Both of these objects expose a method called setScale(int scale) , which sets the type of scale for the encoding to be performed. The method does the same in both cases.

However, this method is absent from any common ancestor (by the way, this OO is the library that I use, and the design does not fit my discretion).

I would like to write a method that takes a DataSizeAction or DataColorAction and calls setScale on this object.

My question is: before I go into individual cases with instanceof , is there a more elegant way to handle this?

Thanks!

+4
source share
2 answers

Can you add interfaces to your hierarchy?

 interface IScalable { void setScale(int scale); int getScale(); } class DataSizeAction extends EncoderAction implements IScalable { ... } class SomeoneElse { private int scale = 2; public void setScale(IScalable scalable) { scalable.setScale(this.scale); } } 
+3
source

Try the following:

  • Create another class that extends EncoderAction
  • Declare setScale as an abstract method inside
  • Let DataSizeAction and DataColorAction extend your new class.

Now you can write your code to refer to instances of the new base class and not call instanceof checks.

NOTE Although I should work here, I would recommend Jonathon respond. Since this is a feature of functionality and has nothing to do with your composition of an object, interfaces are probably suitable.

+3
source

All Articles