• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

structure problem

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a HashMap which contains 2 classes, class A or class B.
I iterate through the HashMap and it returns Objects of either A or B
I want to call a certain function of A or B called "doSomething()", but I also have to get a String from that class that is specific to that Object.


So I didn't know to what class to cast the object.
in my first attempt I created a third class that extends JPanel, with a variable that would be set to the type of class the object was:



so that I could cast the object to C and get the type of class variable and cast it based on what typeofclass it was.

Then i remembered interfaces.
I'd just implement an interface with doSomething() and cast my Object from the HashMap to that interface.
But interfaces only have final variables...right? what If I had variables I needed to access of the implementing classes?



ugh im stuck. help please.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Except in extraordinary circumstances, non-final member variables should be private, anyway. Just add a getVariable() method to the interface, have both A and B implement it by returning the value of their variable. The interface itself then needn't have any member variables in it -- just the method you'll use to fetch the value.
 
A. Wolf
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
oh heh.. thanks so much that works perfectly.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic