Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# explicit casting

atif toor
Greenhorn
Posts: 9
suppose there r two classes class A and class B.Class A is parent class of B
A
|
B
1)A a=new A();
2)B new b=(B) a;
plz explain these two statements.
Explain downward casting.

Jyotsna Clarkin
Ranch Hand
Posts: 158
<html>
<body>
<pre>

Shape

---------|---------
| |
| |
Polygon Circle
|
|
----------
| |
| |
Triangle Square

legend: blue (concrete) class
red interface

<pre>

Consider the inhertance hierarchy in the diagram
The base class Shape is an interface here.
Polygon and Circle implement interface Shape.
Triangle and Square are subclass of Polygon
Now let's look at a range of straightforward declarations
Polygon polygon = new Polygon();
Circle circle = new Cirle();
Triangle triangle = new Triangle();
Square square = new Sqaure();
But we can also declare an object reference and
intialize it to contain any of it's subclasses.
Shape s2 = new Polygon();
Shape s3 = new Triangle();
Shape s4 = new Circle();
Shape s5 = new Square();
Because a Shape is any Shape (Polygon, Circle, Triangle or Square)
We can also say
Triangle t1 = new Triangle();
Shape s6 = t1;
This is upcasting or moving up the inheritance hierarchy.
Which means we declare an object reference of the base-type or it's interface
and assign to it an object of the subclass or class that implements the interface
Simple and easy as long as we don't violate the lines of inheritance
For example, you can't declare or cast a Square into a Circle
Circle c1 = new Square();
Downcasting is moving down the hierarchy and requires an explicit cast.
You can downcast as far down the hierarchy as the ACTUAL object created.
Square sq = (Square) s5 ;
Polygon poly = (Square) s5 ;
(1)A a = new A();
(2)B b = (B) a;
(2) will not work because a is actually an object of type A.
However, if you wrote
A a = new B();
B b=(B) a;
it would.
You should write a lot of small programs and play around with these concepts
regards,
Jyotsna
</pre>
</body>