Sunday, March 8, 2009

simple object type casting



package funds;
class One
{
void show1()
{
System.out.println("one class method");
}
}
class Two extends One
{
void show2()
{
System.out.println("two class method");
}
}
public class TypeCastEx3 {
public static void main(String are[])
{
// super class reference to refer to super class object
One o;
o=new One();
o.show1();

//Sub class reference to refer to sub class object
Two t;
t=new Two();
t.show2();
t.show1();

// super class reference to refer to sub class object
One o1;
o1=(One)new Two();
o1.show1();

//sub class reference to refer to super class object
Two t1;
t1=(Two)new One(); //class cast exception


// narrowing using sub class object
One o3;
o3=(One)new Two();
Two t2=(Two)o3; //If typecast with 'o' get exception
t.show1();
t.show2();
}

}

output:
one class method
two class method
one class method
one class method
one class method
two class method



0 comments:

Post a Comment