Here's the deal:
I have two objects of different classes, a DataSizeAction
and a DataColorAction
. The classes have a common ancestor EncoderAction
not far up the chain.
Both these objects expose a method called setScale(int scale)
which sets a scale type for the encoding they carry out. The method does the same thing in both cases.
However, the method is not present in any common ancestor (btw, this OO is a Library I'm using and the design is not up to my discretion).
I would like to write a method that takes either a DataSizeAction or DataColorAction and calls setScale on that object.
My question is: before I go brute-forcing the separate cases with instanceof
, is there a more elegant way to handle this?
Thanks!
Try this:
EncoderAction
setScale
as an abstract method within thereDataSizeAction
andDataColorAction
extend your new class.Now, you can write your code to refer to instances of the new base class and avoid calling
instanceof
checks.NOTE: Even though what I have here should work, I would recommend Jonathon's answer. Since this is a gaurantee of functionality and doesn't have anything to do with your object's composition, interfaces are likely the way to go.
Can you add interfaces to your hierarchy?