• Post Reply Bookmark Topic Watch Topic
  • New Topic

downward casting of objects  RSS feed

 
faisal usmani
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
faisal usmani
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!