Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

UpCasting DownCasting

 
Thirukumaran Gopalakrishnan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Upcasting DownCasting example please.
 
Paul Anilprem
Enthuware Software Support
Ranch Hand
Posts: 3711
10
 
Louis Moloney
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
example:

ArrayList a = new ArrayList();

Collection c = a; // upcast implicit no need for (ArrayList)a

ArrayList b = (ArrayList)c; // downcast requires explicit cast

upcast dont require an explicit cast as a subclass is always guaranteed to pass the is-a test with its parent. ie ArrayList is a Collection.

downcast requires an explicit cast because the object being cast might not be what its being cast to. You are basically saying to the compiler trust me i know what im doing.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic