Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About casting

 
Jack Lau
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could anyone tell me why runtime error occur ?
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • 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
  • 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
 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thank you very much !!
All are very good and easy understanding examples for me.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic