Java Casting Question

BlueSpud

Registered User
Messages
879
I have a requirement to process a number of different instances of different classes in a similar fashion, like so:

doClass1()
{
..
Class1 obj = (Class1)wigit.get();
process(obj);
..
}

doClass2()
{
..
Class2 obj = (Class2)wigit.get();
process(obj);
..
}

Is there some way that I can abstract out the different classes to give me something like:

doClassX(something??)
{
..
Something?? obj = (something??)wigit.get();
process(obj);
..
}

so that I can call method doClassX() twice with an argument rather than having two almost idenitcal methods.

Thanks in advance.
 
how about creating a superclass which contains your doClassX method, and any attributes that doClassX uses from Class1 and Class2 and then let Class1 and Class2 inherit this new superclass, thus you can call doClassX on your Class1 and Class2 objects.
 
Or even better, why not just have both your classes implement the same (new) interface and then instantiate an instance of this interface. i.e.

doClassX() {
..
InterfaceX obj = (InterfaceX)wigit.get();
process(obj);
..
}

and then Class1 and Class2 would implement InterfaceX

... you would have to declare all public methods that you need to access in the Interface using this approach.
 
coward said:
how about creating a superclass which contains your doClassX method, and any attributes that doClassX uses from Class1 and Class2 and then let Class1 and Class2 inherit this new superclass, thus you can call doClassX on your Class1 and Class2 objects.

As coward says, the doClassX process can be left abstracted in the super class if its to be the same for all subclasses. likewise the super class could be abstracted so that it cant be instantiated only via concrete sub classes..
 
Thanks for the direction. I think my snippet was not clear enough, as the process(), doClass1(), doClass2() are methods of a handler class.

I simply replaced the casting of Class1 & Class2 to Object and everything worked fine, my method doClassX() now looks like this.

doClassX()
{
..
Object obj = wigit.get();
process(obj);
..
}
 
Back
Top