Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cast Object instance to Its Original Type Class again 1

Status
Not open for further replies.

soldieryap

Programmer
Aug 15, 2000
59
0
0
MY
sorry that i mess up the question and thanks for all the guys in my previous question > Object Casting Question < i would like to clearly define my question again.

Away from polymorphism or something else, i would like to know is there any solution/function that can cast an Object type instance to its original Type(eg, Dog)?

eg. Dog dog = new Dog();
Object obj = dog();
((XX) obj).sound(); // how i cast it back?
// and i don't expect to use
// ((Dog) obj).sound();

when i wanna find out the original type of the obj, i use obj.getClass().getName(); but what i want is not find out the Class name it actually is instead of casting that Object type (obj) to Dog. just because of some other reason i have to cast it to Object and i have to cast it back now and perform some function only exist on that Class. and i don't want to use ((Dog) obj).sound(); because i may write lots code of &quot;instanceof&quot; just to test out which Class is actually belongs to.

do u guys got what i mean??
thanks for ur notice and sorry for my poor explaination!
if u still don't understand please state it out.


 
well.. if you don't want to keep rewriting code u know.. all u need to do is write one method like:

public int getAnimal()
or something and just keep calling it.

to get an int or something.

did u read my last post on ur previous post?.. i told u that you don't have to cast the object back into it's original class.. just cast it to it's parent's class and call ur sound method.. wouldn't that save u the hassle?

T
 
i wanna say thanks to you first :)
but the example u showed previously doesn't match my situation, u only used that for stored back boolean and i can't figure out there's any way i can use/modify from ur example to suit my situation. And also Vector.toArray function return as object type, it actually returned back what my question is, doesn't it

what i need is cast the object type instance to its original type and performing a VOID function and the function doesn't existed in Object type instance.

the hierarchy is : Object > Dog extends Object, the function sound() is only existed in Dog class but i have cast it to Object, so how can i cast it back and perform sound() function without do &quot;instanceof&quot; one by one or direct casting (Dog) obj

any ideas?
 
Well first of all, you are correct about the return type of toArray(...). However, this is not relevant since I did not use the returned object. As stated in the api doc:

&quot;Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array. If the Vector fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this Vector.&quot;

If you only need a void function, the answer does lie with polymorphism. Have Dog, Cat, etc. implement an Animal interface that includes the sound() function. Now you can Cast the Object as an Animal and call the sound method. Then, as long as the object implements Animal, the correct sound() will be called. Sample code might look like:
Code:
Object obj = ???;

Animal beast = (Animal)obj;
beast.sound();

By the way, the Boolean class in the previous thread was just used as an example. The crucial code was the middle part and as long as the two unknowns are arrays, it should work for any class. Subsitute Dog for Boolean and sound() for booleanValue() and you should see that it still works.

-HavaTheJut

 
&quot;If you only need a void function, the answer does lie with polymorphism. Have Dog, Cat, etc. implement an Animal interface that includes the sound() function.&quot;

That's exactly what i told him to do on the other post he made.. be it an interface or abstract class.. both will work. I don't think he read my last post or he's just not paying attention to those that want to help.

If you're going to say that u don't know why u should implement an additional class then u seriously have to review the benefits of &quot;object oriented programming&quot; with java.

T
 
I know you said essentially the same thing, but it never hurts to repeat advice :). I really just want to clarify the issue about my polymorphism &quot;work-around&quot;.
 
No.. i'm not saying that u're repeating what i said.. but i'm jus annoyed @ why he'd ask for help.. so i go ahead and give him an advice then he'd totally ignore it.

T
 
actually what the example i showed just a simple example that match my situation! my situation doens't concern about polymorphism, interface and so on ... and sorry about that my english explaination is too poor. And sorry that i don't really understand how ur example can match my situation. would u mind to show me the solution for this situation follow ur theory:

3 classes: Dog, Cat And Fish

eg for Dog class:
public class Dog
{
...
public void sound()
{
...
}
}

function call:
doObject(new Dog()); //or
doObject(new Cat()); //or
doObject(new Fish());

function:
public void doObject(Object obj)
{
????
// i need to cast back to Dog or Cat or Fish to
// perform sound();
}

*** I don't want to cast directly like : ((Dog) ob).sound(); or if (obj instanceof Dog) ...
 
sorry about that, i didn't ignore ur advice and i did post previously to inform that my situation doesn't rely on polymorphism or interface, but just what i post didn't send successfully, that's why i ddin't post another one. that's only one example, sorry about that !! i know the concept polymorphism but my question is not on that.
 
To put all that's been said before into code:
Code:
1 interface: Animal
3 classes: Dog, Cat And Fish

//Animal
public interface Animal
{
  public void sound();
}

//eg for Dog class:
public class Dog implements Animal
{
  ...
  public void sound()
  {
     ...
  }
}

//function call:
doAnimal(new Dog()); //or
doAnimal(new Cat()); //or
doAnimal(new Fish());

//function:
public void doAnimal(Animal beast)
{
   // i need to cast back to Dog or Cat or Fish to
   beast.sound();  //calls the correct sound method
             // if beast is a Dog, Dog.sound() is called
}
And just for the record, this is polymorphism.
 
And before you reply to say that you are not using interfaces... USE AN ANIMAL INTERFACE. It will solve you all the trouble of trying to do something you are specifically not meant to be able to do.
 
sorry, i keep mentioned no interface or Animal class. i created Dog, Cat & Fish is just for an example...

because of some reason i must cast Dog/Cat/Fish to Object and now i have to cast it back to it's original type from object instance, i DON&quot;T have and DON&quot;T need Animal class, please don't create another Animal class for me. coz i don't need them... i just show this this to represent my situation. got what i mean??

i just want to know the solution to cast one instance from Root class to it's sub class

for example : Object cast to Dog
Object cast to Car
Object cast to Human
 
Ok.. can u just tell us what u're really working on instead of giving us examples? I would have to say that if ur example is anything like the &quot;real&quot; thing u're doing then interfaces and abstract classes are the way to go. I come from a computer science discipline and if let me tell you, if i did it any other way than using interfaces and abstract classes my profs would slap me silly.

This is no longer a matter of polymorphism.. interfaces.. abstract classes.. we're not trying to persuade you into doing something u don't like.. we're trying to give u a solution that's clean and efficient!

So either give us the details to the &quot;Real&quot; thing u're doing.. or else we'll not be able to give u ur answer.

T
 
Right, this is how you can do it. Its not pretty, but it works:
Code:
import java.util.*;
import java.lang.reflect.*;

class Dog {
  public void sound() { System.out.println( &quot;Bark&quot; ); }
}
class Cat {
  public void sound() { System.out.println( &quot;Cat&quot; ); }
}

public class Casting {

  private static void stroke( Object o ) {
    Class c = o.getClass();
    try {
      Object g = c.newInstance();
      Method m = c.getMethod( &quot;sound&quot;, null );
      m.invoke( g, null );
    } catch( Exception e ) {}
  }

  public static void main( String[] args ) {

    Object[] pet = {
      new Dog(),
      new Cat()
    };

    for( int i = 0; i < pet.length; i++ )
      stroke( pet[i] );
  }
}
Cheers, Neil
 
BTW: You would do much better to use polymorphism, as we have all shown you. It makes your code so much easier to manage. If you want to run some function called doThis, then simply create an interface like:
Code:
interface DoThis {
  void doThis();
}
Then have all your classes implement this interface. Its only two more words to add to each class definition.
Then change your doObject call to one of:
Code:
public void doObject(Object obj) {
  DoThis generic = (DoThis)obj;
  generic.doThis();
}

OR:

public void doObject(DoThis obj) {
  obj.doThis();
}
It really is the best way to go.
Cheers, Neil :)


 
thanks for all of u guys, i finally find out the answer. and of course i do know the benefits of polymorphism or other OOp techniques, but the reason is my situation doesn't need abstract or interface because the classes i have does not have related to that level.

maybe the code i design not really good enough, but i'm still learning of it :)

i appreciate u guys told me that it's good to use polymorphism !

thanks again!
[noevil]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top