Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to deal with multiple Object classes

 
Jon Swanson
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.


 
Greg Charles
Sheriff
Posts: 2985
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jon Swanson
Ranch Hand
Posts: 216
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.



and I tested it with

 
Greg Charles
Sheriff
Posts: 2985
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looks good to me. I'm glad you got it working!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic