TypeCasting Examples - rahul00773/JavaConcepts GitHub Wiki

Strictly Speaking through type casting we are not creating any new object. For the existing object we are providing another type of reference variable. That is we are performing type casting but not object casting.

String s = new String(“rahul”); These two lines can be written as in single line as —> Object 0 = new String(“rahul”);
Object 0 = (Object)s;

Example 2:

Integer I = new Integer(10); Number n = (Number)I; These two lines can be written as in single line as Object o = new Integer(10); Object o. = (Object)n; Number n = new Integer(10);

System.out.println(n==I); // true System.out.println(o==n); // true

Note:

C c = new C(); class A | (B)c ——> B b = new C(); class B | (A)(B)—— > A a = new C(); class C

Example1:

Class Parent{ m1(){

} }

Class child extend Parent{ m2(){

} }

C c = new C();

c.m1();

c.m2();

((P)c).m1(); // Parent p = new C();

((P)c).m2(); //Invalid

Parent Reference can be used to hold child reference. But using that reference we can’t call child specific methods. And we can call only methods available in parent class

Example 2:

C c = new C(); class A. - > m1(){System.out.println(“A”); c.m1(); //C } ((B)c).m1(); //C | ((A)(B)c)).m1() ;//C class B - > m1(){System.out.println(“B”);} | class C - > m1(){System.out.println(“C”);}

It is overriding and method resolution is always based on Run time object

Example 3:

C c = new C(); class A. - > static m1(){System.out.println(“A”); c.m1(); //C } ((B)c).m1(); //B | ((A)(B)c)).m1() //A class B - > static m1(){System.out.println(“B”);} | class C - >static m1(){System.out.println(“C”);}

It is method hiding, and method resolution is always bases on reference type.

Example4:

C c = new C(); class A. - > int x =777; System.out.print(c.x); /// 999 System.out.print((B)c).x);///888 | System.out.print(((A)(B)c)).x) //999 class B - > int x = 888; | class C - >int x =999;

Variable resolution is always based on reference type. But not based on run Time object.