• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Upcasting and downcasting

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello I just finished reading about upcasting and downcasting. They're a bit tricky to understand, but I think i can get it with time

The only thing the tutorial isn't quite clear on is why they would need to be used if someone can give me an idea I would appreciate it
--thanks
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Davey Lopez wrote:The only thing the tutorial isn't quite clear on is why they would need to be used if someone can give me an idea I would appreciate it


Upcasting (ie, casting to a superclass) is almost never needed, since any subclass (eg, Dog) is its superclass (eg, Animal), so:
Animal a = new Dog();
is perfectly legal.

The simplest example I know of where a downcast is normally required is an equals() method, because it takes an Object, eg, for a Dog:
HIH

Winston
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You should avoid casting whenever possible. It is, however, unavoidable in the equals method.
 
straws are for suckers. tiny ads are for attractive people.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic