English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Trying to make this as simple as possible. I have 30 or so classes that I need to get access to depending which one is showing. To make things easy, let's say I have three classes as members of another class:
Class1, Class2 and Class3.
I only show one at a time. All three have a method called "UpdateData." I need to make a call to UpdateData in whatever one is showing (or active).
How can I hold a reference to the active class so I can make the call? IE, instead of doing something like:
if (Class1.isActive)
Class1.UpdateData()
else if (Class2.isActive)
Class2.UpdateData()
Remember, I have 30 classes. I just want to hold the active class' reference somehow to call it only once. Something like:
ActiveClass[n].UpdateData()
I could add all of the classes in there and then hold the active class as an integer "n." I can't use Vector or anything because that requires a cast to use. I need the class to change. I can't figure this out. Thanks for any help.

2007-07-11 10:54:00 · 2 answers · asked by JIM 1 in Computers & Internet Programming & Design

2 answers

Declare an Interface which has your UpdateData method. Then have your 30 or so classes implement that Interface.

Then declare a variable of the type of the Interface and store the current instance of the active class in it.

e.g.,

interface UpdateIF {
public void UpdateData();
}

class Class1 implements UpdateIF {
public void UpdateData() { ... }
}
// Class2 and Class3 similar

UpdateIF activeInstance = new Class1();
// Or wherever you get the instance
activeInstance.UpdateData();

You can assign any implementer of UpdateIF to activeInstance, so any instance of any of your 30 classes qualify.

You could also declare an array like this:
UpdateIF instances[30];
... and store one instance of each class in it, and then call:
instances[idx].UpdateData();

-------------------
If you're talking about static methods instead, you can declare a variable of type Class and set it to whatever class is current... but then you'll have to use reflection to call the UpdateData() method. This approach would be discouraged.

2007-07-11 10:59:00 · answer #1 · answered by McFate 7 · 0 0

Why do no longer you pass on your checklist as a parameter on your readFile() technique? so which you're able to define readFile() like this: public void readFile(ArrayListf8c8b93cb2e4f297e4b96d4b9c1e98a employeeList) And once you call readFile(), you're able to pass interior the checklist you created on your Catalog classification. notice: continually use popular collections while a threat (i.e., ArrayListf8c8b93cb2e4f297e4b96d4b9c1e98a as a replace of basically ArrayList).

2016-11-09 01:45:32 · answer #2 · answered by ? 4 · 0 0

fedest.com, questions and answers