File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes structure problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "structure problem" Watch "structure problem" New topic

structure problem

A. Wolf
Ranch Hand

Joined: Sep 28, 2003
Posts: 57
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.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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.

[Jess in Action][AskingGoodQuestions]
A. Wolf
Ranch Hand

Joined: Sep 28, 2003
Posts: 57
oh heh.. thanks so much that works perfectly.
I agree. Here's the link:
subject: structure problem
It's not a secret anymore!