Object TypeCasting: - rahul00773/JavaConcepts GitHub Wiki

We can use Parent reference to hold child objects.

Ex : Object o= new String(“Durga”);

We can use Interface reference to hold the implemented class Objects.

Ex. Runnable r = new Thread();

A. b = (C) d;

A= class/Interface name b= name of reference variable C=class/Interface name d=reference variable name

Point 1: (Compile Time checking 1): The type of 'd' and ‘C’ must have some relation. Either child to parent or parent to child or same type. Otherwise, we will get a compile-time error saying: Inconvertible types found d type required C

Ex. Object o = new String(“rahul”); StringBuffer sb =(StringBuffer)o;

Example2:

String s = new String(“Rahul”); StringBuffer sb =(StringBuffer)s;

Compile Type will come: Inconvertible types found :java.lang.string required: java.lang.StringBuffer .

Point2:(Compile-time checking 2): ‘C’ must be either same or derived type of ‘A’. Otherwise, we will get a compile-time error saying Incompatible types found C: Required: A

Ex:1

Object o = new String(“rahul”); StringBuffer sb =(StringBuffer)o;

Ex2: Object o = new String(“rahul”); StringBuffer sb = (String)o;

Compile Time Error: Incompatible types: found :java.lang.string required: java.lang.StringBuffer .

Point3(Run time checking3:) RunTime object type of ‘d’ Must be either same or derived type of ‘C’. Otherwise, we will get run time exception saying ‘class cast exception’.

Ex:1

Object o = new String(“rahul”); StringBuffer sb =(StringBuffer)o;

We, Will, get RunTime exception saying: Class cast exception. java.lang.String can not be cast to java.lang.StringBuffer

Ex2: Object o = new String(“rahul”); Object o1 = (String)o;