This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "explicit casting" Watch "explicit casting" New topic
Author

explicit casting

atif toor
Greenhorn

Joined: Apr 27, 2001
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.
Thankz in advance
Jyotsna Clarkin
Ranch Hand

Joined: Jan 26, 2001
Posts: 158
<html>
<head>
<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 ;
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
regards,
Jyotsna
</pre>
</body>
</head>
</html>

[This message has been edited by Jyotsna Clarkin (edited May 10, 2001).]
 
Don't get me started about those stupid light bulbs.
 
subject: explicit casting
 
Similar Threads
Object casting
Casting
What does casting actually change?
down cast only throw exception
Thread constructor