Do you mean using a Number object where an Object is required (just an example)?
All classes in Java can be used wherever one of their super-classes is specifically mentioned. Since sub-classes extend a super-class, they have all the properties the super-class has (and then some). The sub-class is not actually converted, though, its additional properties are just ignored in that moment.
But that's such a fundamental (and basic) concept in Java that I am wondering if I misunderstand what you're asking?
Java decides which instance method to call at runtime ("late binding"), based on the actual type of underlying object (not the reference type).
Hope this helps...
Ronnie Ho
Ranch Hand
Joined: Aug 10, 2005
Posts: 47
posted
0
ClassA1 A1 = (ClassA1) B1;
Just a note. There is no need to explicit type cast "(ClassA1)B1". The compiler does it implicitly for you.
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
Casting doesn't change the type of an object, just the type of the reference. After the casting, the ClassB1 object will still be a ClassB1 object - it's just referenced by a ClassA1 reference variable.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Sathya Srinivasan
Ranch Hand
Joined: Jan 29, 2002
Posts: 379
posted
0
You can always go from specific to general without any need to typecast. For example, if you have a Vehicle class and a Car class (which is a subclass of Vechicle class), then
is perfectly legal since any car is essentially a vehicle. As Ilja mentioned, calling "car" as a vehicle doesn't change the fact that it is still a "Car". It is just seen as a Vehicle. That's all.
However, if you want to convert the Vehicle back to a car
you need an explicit typecast (called downcasting), as you don't know what the Vehicle actually is.
Originally posted by Mathew Chen: Hi, I am kinda confused about upcasting in Java?I thought converting a subclass to a super class is not possible.
Pls advice.
Thanks Mathew Chen
First off there is no "conversion" in Java per se. You are simply changing the variable type that references the same object. Second, I believe you have the concept upside down. You can always reference a sub-type using a super-type reference:
Object foo = new String("Billy Bob Jolie");
This is upcasting and it's risky:
String bar = (String)foo;
If you are just kidding about foo being a String your thread will crash.