Object casting in java

 Object casting in java:

A b = (C)d

A - Class or Instance Name

b - Reference Variable Name

C - Class or Instance Name

d - Reference Variable Name

3 Golden rules:

Rule 1: (checked  by compiler)

There should be parent/child relation between C and d, object reference d should be child or parent of Class C else compiler will throw inconvertable compilation error.


Eg:String o=new String("hellboymaddi");
      StringBuffer b=(StringBuffer)o;

In the above example, reference variable o is of String type and there is no parent & child relationship with String Buffer,so it will raise compilation error and exact message is:

inconvertible types
found: java.lang.String
required: java.lang.StringBuffer


Rule 2: (Checked by compiler)

We are assigning class C to Class A,so Class c Should be equal to Or child Class of A, else compiler will throw incompatible compilation error.

Eg:Object o=new String("hellboymaddi");
      String b=(StringBuffer)o;

In the above example, we are trying to assign StringBuffer Object reference to String Object reference and String is not parent of StringBuffer,so it will raise compilation error and exact message is:
incompatible types
found: java.lang.StringBuffer
required: java.lang.String

Rule 3: (Resolved at Runtime, so checked by jvm)

Jvm will check runtime object type of d, if above 2 rules are passed by compiler.The runtime object d should be same or derived type of Class C, else we will get RunTimeException saying ClassCastException.

Eg:Object o=new String("hellboymaddi");
      StringBuffer b=(StringBuffer)o;

In the above example, Runtime object type of 'o' is String which is neither equal to StringBuffer or its derived class,so it will raise ClassCast RunTimeException.

Exception in thread "main" java.lang.ClassCastException:java.lang.String cannot be cast o java.lang.StringBuffer

Examples



Golden Rule:
Class Parent{
void m1(){
sop("parent class m1");
}
}
Class Child extends Parent{
void m1(){
sop("child class m1")
}
void m2(){
sop("child class m2")
}
}

Parent obj=new Child();

obj.m1(); //child class m1
obj.m2();// compilation error

Note:If we call a method over  object reference,it will check method is available in reference type class almost all the times, But in case of overding(runtime polymorpism) only runtime object type will be checked by jvm.

Parent obj=new Child();
If(there is method overiding){
runtime object type is considered
}
else{
reference ype is considered
}



Comments