多态练习

选择题

  1. D
  2. C
  3. A
  4. C
  5. A
  6. B
  7. B
  8. AD
  9. B

编程题

package javabean;
//父类
public abstract class Animal {
     
    private String kind;

    public Animal(){
     

    }
    public Animal(String kind){
     
        this.kind=kind;
    }

    public String getKind() {
     
        return kind;
    }

    public void setKind(String kind) {
     
        this.kind = kind;
    }

    public abstract void cry();
}
package javabean;

/**
 * Cat
 */
public class Cat extends Animal{
     

    public void cry(){
     
        System.out.println("喵喵喵~~~");
    }
}
package javabean;

/**
 * Dog
 */
public class Dog extends Animal {
     

    public void cry(){
     
        System.out.println("汪汪汪~~~");
    }
}
package javabean;
/**
 * Sheep
 */
public class Sheep extends Animal{
     
    public void cry(){
     
        System.out.println("咩咩咩~~~");
    }
}
//测试类
package javabean;

import java.util.Random;

public class Test2 {
     
    public static void main(String[] args) {
     
        Animal[] arr=new Animal[5];
        for (int i = 0; i < arr.length; i++) {
     
            Random r=new Random();
            int num=r.nextInt(3);
            switch(num){
     
                case 0:arr[i]=new Cat();
                break;
                case 1:arr[i]=new Dog();
                break;
                case 2:arr[i]=new Sheep();
                break;
                default:
                break;
            }
        }
        
        for (Animal animal : arr) {
     
            animal.cry();
        }
    }
}

你可能感兴趣的:(java,java)