复用类

来源:互联网 发布:阿里云总部在哪里 编辑:程序博客网 时间:2024/05/17 06:56

程序如下:

package reusing; 

 
class Frog2 extends Amphibian { 
  public void moveInWater() { 
    System.out.println("Frog swimming"); 
  } 
  public void moveOnLand() { 
    System.out.println("Frog jumping"); 
  } 

 
public class E17_Frog2 { 
  public static void main(String args[]) { 
    Amphibian a = new Frog2(); 
    a.moveInWater(); 
    a.moveOnLand(); 
  } 
} /* Output: 
Frog swimming 
Frog jumping 

*///:~ 

基类Amphibian中也定义了moveInwater和moveOnland方法。

要点:Since the compiler has a reference to an Amphibian, you might guess it will call
the Amphibian methods. Instead, it calls the Frog2 methods. Since a is indeed
a reference to a Frog2, this is the appropriate result. That’s polymorphism: The 
right behavior happens even if you are talking to a base-class reference. 

原创粉丝点击