I am using some code that has a series of classes like Line, Text, Box which all extend Object. The have the same methods like setPosition() and write(). I don't have any control over the classes or the methods in them, other than the fact I can extend them.
I will be using the same set of them repeatedly (for example, a specific set of Text, Text, Line, Box), I am trying to implement something of the form:
The compile complains that component does not have methods like setPosition and write (well, says it can't find the symbol).
I am not quite sure which direction to go. I can add a bunch of instanceof statements (I think)-
But there is the maintainability of keeping track of what the objects might be that have the write and setPosition methods. I may use more in the future.
Am I thinking about this problem the right way? Before I start adding a lot of code to make the program work, could someone comment on how something like this should be structured? I think basically the classes should have an interface that has the common methods and my ArrayList should start from there, but I can't change those classes.
There are certain languages that are "duck typed". That means if you're sure the method exists in a class, you can call it. The compiler won't complain, but you'll get a big runtime exception if the method doesn't actually exist.
Java isn't duck typed. You have to call a method that the compiler can see exists in the class you're calling it on, or in an interface the class implements. Your classes don't extend from or implement anything that contains those methods so you're out of luck. However, you said you can extend those classes. If you make an interface, say Common, with your two methods and do something like:
Then assuming you can instantiate CommonBlocks, CommonLines, etc., you can cast everything to Common and work with them like that.
Joined: Oct 10, 2011
Here is a simple test implementation (I've actually got the classes in separate files). Have I understood you correctly? It all seems to work quite nicely.