This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes downward casting of objects Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "downward casting of objects " Watch "downward casting of objects " New topic
Author

downward casting of objects

faisal usmani
Ranch Hand

Joined: Jan 14, 2006
Posts: 139
Hello ,
Under which circumstances downward casting of objects is allowed and under which it is prohibited .

Please give a working example if possible

Thanx in advance


regards
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24081
    
  15

A cast can never change the type of an object; it just tells the compiler something that it doesn't know. If you have a class Animal and two subclasses Cat and Dog, then you can cast a variable of type Animal to type Cat if, and only if, that variable actually contains a Cat (or null, I suppose, to be complete.) You can never convert an instance of one class into another with a cast: if you really have an Animal object, or a Dog, it's not legal to cast it to a Cat.


[Jess in Action][AskingGoodQuestions]
faisal usmani
Ranch Hand

Joined: Jan 14, 2006
Posts: 139
Thanx sir ,

I got the point , but it will be really a great help if you give me a small woking code :roll:

Thanx in advance

regards
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24081
    
  15

Originally posted by faisal usmani:
T but it will be really a great help if you give me a small woking code


Of what, exactly? This is a legal downcast:

import java.awt.*;

Component c = new Button("OK");
Button b = (Button) c;

while this is not:

Component c = new Label("OK");
Button b = (Button) c;
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: downward casting of objects
 
Similar Threads
Cannon fire
Casting
is it possible to cast a string to class or object
casting objects
Is Zirf Slavic?