This is the topic that had shown me stars during day ! Every time when i read any java book i felt that i am pretty clear with this & can handle any type of Qs but every time i failed .
polymorphism is simple concept of deciding at run time which object's method to be called .
Here i will paste few examples where i was most confused
case 1
class ABC {
private int a=10;
int getA ( )
{return a;}
}
class BCD extends ABC{
private int a=20;
int getA ( )
{return 2*a;}
}
public static void main(Strings args[])
{
ABC a = new ABC();
s.o.p ( a.getA( ) ) ;
BCD b = new BCD();
s.o.p ( b.getA( ) ) ;
// b=a; Compiler Error
b = ( BCD ) a; // Need to type cast explicitly
s.o.p ( b.getA( ) ) ; // ClassCastException at run time
}
Reason 1
Compiler will error because upcasting is not automatic in java
ClassCastException will come when the object reference of base class point to base class object .
to remove that
a = new BCD ( ) ;
b= ( BCD ) a;
....to be continued ....
polymorphism is simple concept of deciding at run time which object's method to be called .
Here i will paste few examples where i was most confused
case 1
class ABC {
private int a=10;
int getA ( )
{return a;}
}
class BCD extends ABC{
private int a=20;
int getA ( )
{return 2*a;}
}
public static void main(Strings args[])
{
ABC a = new ABC();
s.o.p ( a.getA( ) ) ;
BCD b = new BCD();
s.o.p ( b.getA( ) ) ;
// b=a; Compiler Error
b = ( BCD ) a; // Need to type cast explicitly
s.o.p ( b.getA( ) ) ; // ClassCastException at run time
}
Reason 1
Compiler will error because upcasting is not automatic in java
ClassCastException will come when the object reference of base class point to base class object .
to remove that
a = new BCD ( ) ;
b= ( BCD ) a;
....to be continued ....
No comments:
Post a Comment