设计一个动物接口,并设计相应的动作,例如跑、跳、走等。再设计一个狗类实现这个动物接口,该狗类具有一些基本属性,例如名称、大小、体重等。编写测试类测试是否达到预定功能。要求使用自定义的包。
 
【正确答案】package test.demo;
   public interface Animal{
   public void run( );
   public void walk( );
   public void jump( );
   }
   package test. demo;
   public class Dog implements Animal{
   private String name;    //名称
   private int bodySize;    //大小
   private float weight;//体重
   public Dog(String name, int bodySize, float weight){
   super( );
   this.name=name;
   this.bodySize=bodySize;
   this.weight=weight;
   }
   public String getName( )}
   return name;
   }
   public void setName(String name){
   this.name=name;
   }
   public int getBodySize( ){
   return bodySize;
   }
   public void setBodySize(int bodySize){
   this.bodySize=bodySize;
   }
   public float getWeight( ){
   return weight;
   }
   public void setWeight(float weight){
   this.weight=weight;
   }
   public void run( ){
   System.out.println("I'm running!");
   }
   public void walk( ){
   System.out.println("I'm walking!");
   }
   public void jump( ){
   System.out. println("I'm jumping!");
   }
   public String toString( ){
   return ("I'm a"+name+
   ", my body size is"+bodySize+
   ", and myweightis"+weight+".");
   }
   public static void main(String[ ] args){
   Dog ani=new Dog("tady",5, 10.5f);
   System.out.println(ani.toString( ));
   ani.run( );
   ani.jump( );
   ani.walk( );
   }
   }
【答案解析】 接口可被看成纯虚函数,它里面的所有方法需要子类来实现。