Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Type Casting
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..
hierarchy) 5. X xz = new Z(); // compiles ok (up the hierarchy) 6. Y yz = new Z();// incompatible type (siblings)
Cont..
hierarchy) 5. X xz = new Z(); // compiles ok (up the hierarchy) 6. Y yz = new Z();// incompatible type (siblings)
Cont..
(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)
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
THANK YOU!