• 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

About casting

 
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could anyone tell me why runtime error occur ?
 
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following code example demonstrates why a base class can not be cast to a sub class.

A sub class is more specialized than a base class. Since the base class does not have the specialized behavior of the sub class it is not possible to cast an instance of a base class to a sub class type.
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is important to remember that when you cast an instance of an object from one type to another the object instance is not modified in any way. Instead, the only thing that changes is the view of the object. For example, when a subclass such as Dog is cast to the base class, Pet, the view of the Dog instance is narrowed to a Pet base class view. A reference of type Pet can only access the members of the Dog subclass that are declared in the Pet base class.


Of course, the rules of member inheritance and hiding apply as demonstrated by the following code.

Prints: A.s1,B.m1,A.m2
 
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In a line, upcast is legal but downcast is not...
 
Jack Lau
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much !!
All are very good and easy understanding examples for me.
 
reply
    Bookmark Topic Watch Topic
  • New Topic