• Post Reply Bookmark Topic Watch Topic
  • New Topic

Upcasting and downcasting  RSS feed

 
Davey Lopez
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • 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
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • 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
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should avoid casting whenever possible. It is, however, unavoidable in the equals method.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!