多态是面向对象的一个很重要的特性,然而其中有些细节容易使人混淆。
其实说白了多态就是根据实际对象(而不是引用)来调用相应的方法:其中包括在该对象调用过程所引起的整个调用链上的所有调用都是基于该对象的。
如:
class Father
{
public int getCount()
{
System.out.println("father's getCount()");
return 0;
}
public void overRideMethod()
{
getCount();
}
}
public class Override extends Father
{
private int count=0;
public int getCount()
{
count++;
System.out.println("son's getCount()="+count);
return count;
}
public void overRideMethod(){
super.overRideMethod();
}
public static void main(String[] args)
{
new Override().overRideMethod();
}
}
在上面的new Override().overRideMethod()的调用过程会引起 super.overRideMethod();
的调用从而又会调用getCount()方法(注意在此调用中是调用的Override类中的getCount()方法)。
