| 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
|
|
|
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
|
|
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;
|
 |
 |
|
|
subject: downward casting of objects
|
|
|