Object Casting in Java Runtime Polymorphism | Java Online Concepts

This Java Online Concepts “Object Casting in Java Runtime Polymorphism” is providing clear information about dynamic binding including up casting and down casting in java inheritance.


 

Up casting:

  • Storing Child object into Parent type object reference variable.
  • Up casting is implicit in java.
  • In case of Hierarchical and Multi-level inheritance, number of Child objects having single Parent.
  • Hence while up casting, no chance of deviation.

 

  • We cannot cast Parent object to Child.
  • It generates Runtime Error called ClassCastException.
  • The following example explains the concept clearly….

 

  • We can implement Runtime Polymorphism using Interfaces & Abstract classes.
  • Overriding specifications of interface and abstract class is the concept of Runtime polymorphism.
  • Overriding is the concept of Runtime binding.
  • Hence we use interfaces and abstract classes in to implement dynamic binding.

Down casting in Java

  • We can access Tenant1 using Owner
  • We can’t access Tenant1Friend functionality using Owner
  • Suppose if we access Tenant1Friend using Owner, results Error.
  • If ‘Owner’ pass that information to Tenant1 (Downcast), then accessing is possible.
  • Please go through diagram and implementation carefully.

 

Share this