File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes explicit casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "explicit casting" Watch "explicit casting" New topic

explicit casting

atif toor

Joined: Apr 27, 2001
Posts: 9
suppose there r two classes class A and class B.Class A is parent class of B
1)A a=new A();
2)B new b=(B) a;
plz explain these two statements.
Explain downward casting.
Thankz in advance
Jyotsna Clarkin
Ranch Hand

Joined: Jan 26, 2001
Posts: 158


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

legend: blue (concrete) class
red interface


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 ;
So for your 2 statements
(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

[This message has been edited by Jyotsna Clarkin (edited May 10, 2001).]
I agree. Here's the link:
subject: explicit casting