• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about polymorphism!

 
dragon ji
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
follows the code:
class Base {
int i=99;
public void amethod(){
System.out.println("Base.amethod()");
}
}
public class RType extends Base{
int i=-1;
public static void main(String argv[]){
Base b = new RType();//<= Note the type
System.out.println(b.i);
b.amethod();
}
public void amethod(){
System.out.println("RType.amethod()");
}
}
the answer is :Note how the type of the reference is b Base but the type of actual class is RType. The call to amethod will invoke the version in RType but the call to output b.i will reference the field i in the Base class.
But I can't understand why the call to output b.i will reference the field i in the Base class?

 
Manish Hatwalne
Ranch Hand
Posts: 2595
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The methods exhibit dynamic polymorphism, i.e. overriding. Not the member variables.
HTH,
- Manish
 
dragon ji
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh,I get it now.thanx
 
Don Bosco
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Manish,
Dynamic Polymorphism and Overriding are not synonymous. Dynamic Polymorphism occurs when subclass methods are called using base class reference. When you are not using base class reference, it is Compile Time Polymorphism.
//Dynamic Polymorphism
Base b = new Derived();
b.OverridenMethod();
//Compile Time Polymorphism
Derived d = new Derived();
d.OverridenMethod();
If you already know this then just ignore this message. No hard feelings.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic