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!

Object Casting question

Status
Not open for further replies.

soldieryap

Programmer
Aug 15, 2000
59
0
0
MY
i wonder if there's solution to cast Object instance to its original Class Type without knowing its original type

for example:

Dog dog = new Dog();
Object obj = (Object) dog;

is there possible to cast "obj" to its original type without the code like:
Dog anotherDog = (Dog) obj;

got what i mean??
thanks in advanced . . .
 
You can only cast objects back to their unknown original types by checking each type individually.

For example:
Code:
public static void main(String args[])
{
  Object obj = new Boolean(true);

  Double myDouble = castDouble(obj);
  System.out.println("Double: "+myDouble);
  if (myDouble != null)
  {
    System.out.println("It's a Double");
  }

  Boolean myBoolean = castBoolean(obj);
  System.out.println("Boolean: "+myBoolean);
  if (myBoolean != null)
  {
    System.out.println("It's a Boolean");
  }
}

public static Double castDouble(Object obj)
{
  Double result = null;
  try
  {
    result = (Double)obj;
  }
  catch (ClassCastException eCast)
  {}
  return result;
}
public static Boolean castBoolean(Object obj)
{
  Boolean result = null;
  try
  {
    result = (Boolean)obj;
  }
  catch (ClassCastException eCast)
  {}
  return result;
}
 
lets take the 2 cases;

class Object
{
}

class Dog extends Object
{
}

Object obj=new Object();
Dog d=new Dog();


Assigning up the hierarchy is a cake walk
ex/-
obj=d;

Assigning down the hierarchy, you need to be explicit.
d=(Dog)obj;

Why assigning down the hierarchy you need to be more cplicit is because the classes subclasses are likely to have more functionality than the base classes. So if you assign a base class to a subclass instance it follows that you can access the extra subclass functionality from the base class instance, which is sadly not possible. So the compiler make you cast if you are going down the hierarchy. It's like asking you for a verification that what you are doing sounds strange but you are responsible.

However another check at run time is done to check if its really possible to cast an Object to a Dog.















 
what actually i meant was casting to unknown type without checking my own class one by one, because once i have a lot of classes, i have to make bundle of code just for checking what type it original is.

for example again:
1. Animal extends Object
2. Dog extends Animal
3. Cat extends Animal
4. Fish extends Animal

now, both Dog, Cat, Fish have same function: public void sound().

Assume i have instance :
Dog myDog = new Dog();

and i cast myDog to object:
Object obj = (Object) myDog;

now, i want to cast back obj to its original type and perform function > sound(); <, assume i don't know there's Classes of Dog, Cat and Fish. So how can i cast back &quot;obj&quot; to Dog without checking my classes one by one?

thanks for replied, but any other solution that can provide?
 
from what I understand, you have provided individual implementations of a method sound() in Cat, Dog, Horse ,etc

Now you want to call the instance's corresponding method. Instead of casting the Object to Animal, Dog, Horse, Cat , etc you declare a method called sound() in the superclass and override in the sub classes. Then if you invoke the obj.sound() it will internally invoke the Dogs or Cats or Horses method , depending on the value assigned to obj.



NO YOU CANNOT ASSIGN AND OBJ TO DOG. THE COMPILER WOULD NOT ALLOW YOU UNTIL YOU PERFORM A CAST

 
hrm ... ! that's what i know, but now i need a solution to cast and obj to its original type and perform sound() function.

normally we do to cast object to another type and perform the sound() function by:
((Dog) obj).sound();

but assume that i don't know what it original type is, how can i cast back my obj to Dog object?

((???) obj).sound();

i tried Class object but failed!! can't i cast it back?
 
Correct me if I'm wrong but don't you just want polymorphism?

Code:
interface Animal {
  void sound();
}

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

class Cat implements Animal {
  public void sound() {
    System.out.println( &quot;Meow&quot; );
  }
}

public class Menagerie {
  public static void stroke( Animal a ) {
    a.sound();
  }
  public static void main( String[] args ) {
    Animal[] pet = {
      new Dog(),
      new Cat()
    };
    for( int i = 0; i < pet.length; i++ )
      stroke( pet[i] );
  }
}
Should return:
Code:
Bark
Meow
There is no need to recast to the subclass - polymorphism does this for you [apologies if there are any bugs in the code - I can't test this at the moment :-(]
Cheers, Neil :)
 
A child object can be assigned as a parent object without casting i.e:
Child child = new Child();
Parent pChild = child;

but u can't do it the other way around.. a parent handle holding a child object must be CAST.. i.e:
Parent pChild = new Child();
Child child = (Child)pChild;

if u're afraid that u might be casting an object into something it isn't then just use the &quot;instanceOf&quot; operator to test to see if it's true then cast.. other wise throw an exception or watever.

T
 
Good news, soldieryap, I have done the impossible. :)
I used the runtime-dynamic behavior of Vector.toArray(Object[]), but this method is rather quirky.
This method only allows you to work with arrays, but if you use foo[0] just like a single variable, this isn't a real problem. (I believe this requires 1.4.0+)
Code:
// Goal: get obj[0] (Object) into foo[0] (unknown)

// unknown stuff
Boolean[] foo = { new Boolean(false) };
Object[] obj = { new Boolean(true) };
// method specific to FooClass (Boolean)
System.out.println(&quot;foo[0] before: &quot; + foo[0].booleanValue());

// Assuming obj and foo arrays
// 1. are not null (if necessary,
//   instantiate with: 'new FooClass[0];')
// 2. foo.length >= obj.length
//   (see Vector.toArray(Object[]) for reason)
// assign obj to foo.
Vector v = new Vector();
v.add(obj[0]);
try
{
  v.toArray(foo);
}
catch (Exception e)
{
  System.out.println(e);
}

// the value has now been set
// without knowing the type of foo or obj
// except that they are Object arrays
System.out.println(&quot;foo[0] after: &quot; + foo[0].booleanValue());
However, I would be hesitant to use this because it kinda goes against the whole idea of polymorphism...

-HavaTheJut
 
Is animal an abstract class? (it wouldn't matter tho.. be a an abstract or real class.. or even an interface).. does the animal class have the method sound? if so then just call it.. u don't have to cast the object back to it's original class.. just cast it to animal and call the method (i'm assuming ur dog cat and fish got the sound() method from their parent, the animal class). Polymorphism would call the right method.

I've said this and I'll say it again,
&quot;YOU DO NOT HAVE TO CAST a dog object into an object!!!&quot;
Dog dog = new Dog();
Object obj = dog;
THIS IS CORREcT.. no need to put (Object) beside dog. U only need to cast when u're trying to turn an object with a parent handler into a child class!!!

Here's another example.. say we have a credit card class and a airmiles credit card class which is a child of the credit card class.. (the airmiles just gives us airmiles points for every 20 dollars). This means that they both have a charge() method rite? but the child class's charge method should be different since it needs to update a instance variable say, int points;

If u try to do something like:
CreditCard airmilesCreditCard = new AirmilesCreditCard();
then do something like airmilesCreditCard.chrage(100);

polymorphism would NOT.. i repeat WOULD NOT call the CreditCard's charge method. It would call the appropriate one.

Hope this help.
Good luck.

Terence
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top