Sei sulla pagina 1di 11

OBJECT TYPE CASTING

Type Casting

Converting an object of one class to an

object of another class is possible if the object types are compatible. Java will perform some conversion automatically. Such conversions are known as implicit type casting. Conversions forced by the programmer is known as explicit type casting.

Eg.,
X PERSON

TEACHER

STUDENT

Z1

Z2

UG_STUD ENT

PG_STUD ENT

Class definition
public Class X { public void F(); public void F1(); } // X is a super class of Y and Z which are sub classes. Class Y extends X { public void F(); public void F2a(); } Class Z extends X { public void F(); public void F2b(); }

Cont.,
Class Z1 extends Z { public void F(); public void F3a(); } // Z1,Z2 are subclasses which is derived from Z. Class Z2 extends Z { public void F(); public void F3b(); }

Cont..

1. X x = new X(); //no casting required

2. Y y = new Y(); //no casting required


3. Z z = new Z(); //no casting required 4. X xy = new Y(); // compiles ok (up the

hierarchy) 5. X xz = new Z(); // compiles ok (up the hierarchy) 6. Y yz = new Z();// incompatible type (siblings)

Cont..

1. X x = new X(); //no casting required

2. Y y = new Y(); //no casting required


3. Z z = new Z(); //no casting required 4. X xy = new Y(); // compiles ok (up the

hierarchy) 5. X xz = new Z(); // compiles ok (up the hierarchy) 6. Y yz = new Z();// incompatible type (siblings)

Cont..

1. Y yz = new Z(); //incompatible type 2. 3. 4. 5.

(siblings) Y y1 = new X(); //incompatible. X is not a Y Z z1 = new X(); //X is not a Z X x1 = y; // compiles ok (y is subclass of X) X x2 = z; // compiles ok (z is subclass of X)

Object type Casting

Y yx = (Y) x1; // compiles and runs ok (x1 is type Y) Z zx = (Z) x2; // compiles and runs ok (x2 is type Z) // X xy = new Y(); (declared earlier) xy.F(); //calls method F() of class X ((Y)xy).F(); //explicitly type cast xy to method call F() class Y ((Y)xy).F2a(); // call the method F2a() from class Y

Object Type Casting.,


X xz1=new Z1(); ((Z1)xz1).F();//calls method F() in class Z1 ((Z1)xz1).F1();//calls method F1() in class X ((Z1)xz1).F2b();//calls method F2b() in class Z ((Z1)xz1).F3a();//calls method F3a() in class Z1

THANK YOU!

Potrebbero piacerti anche