zoukankan      html  css  js  c++  java
  • java新手笔记15 多态

    1.Animal类

    package com.yfs.javase;
    public class Animal {
    	
    	public void cry() {
    		System.out.println("动物叫...");
    	}
    
    }
    

     2.Dog/Cat/Bird类

    package com.yfs.javase;
    
    public class Dog extends Animal {	
    	public void cry() {
    		System.out.println("汪 汪...");
    	}
    }
    
    class Cat extends Animal {
    	public void cry () {
    		System.out.println("喵 喵...");
    	}
    }
    
    class Bird extends Animal {
    	public void cry () {
    		System.out.println("嘎 嘎...");
    	}
    }
    

     3.Box类,(集合)

    package com.yfs.javase;
    
    public class Box {
    	// 动物房在哪里 10個動物
    //	private Dog[] dogs = new Dog[10];
    //	private Cat[] cats = new Cat[10];
    //	private Bird[] birds = new Bird[10];
    	//声明父类数组
    	private Animal[] animals = new Animal[10];
    	private int index = 0;
    
    	// 装动物
    	public void addAnimal(Animal pet) {
    		if (index >= 10) {
    			System.out.println("箱子已满");
    			return;
    		}
    		animals[index] = pet;
    		index++;
    		//System.out.println(pet);
    	}
    //	
    //	public void addAnimal(Cat cat) {
    //		if (index >= 10) {
    //			System.out.println("箱子已满");
    //			return;
    //		}
    //		cats[index] = cat;
    //		index++;
    //	}
    
    	// 踢箱子
    	public void kid() {
    
    		for (int i = 0; i < animals.length; i++) {
    			animals[i].cry();//执行的是子类的方法 多态  覆盖的方法
    		}
    	}
    
    }
    

     4.Box测试

    package com.yfs.javase;
    
    import java.util.Random;
    
    public class BoxTest {
    
    	public static void main(String[] args) {
    		Box box = new Box();
    //		box.addAnimal(new Dog());
    //		box.addAnimal(new Bird());
    //		box.addAnimal(new Cat());
    		Random ran = new Random();
    		for (int i = 0; i < 15; i++) {
    			int r = ran.nextInt(101);//  100   65  35  
    			if(r > 65) {
    				box.addAnimal(new Dog());
    			} else if( r > 35) {
    				box.addAnimal(new Cat());
    			} else {
    				box.addAnimal(new Bird());
    			}
    		}
    		
    		box.kid();
    
    	}
    
    }
    
  • 相关阅读:
    Spring 声明式事务管理(11)
    Spring JdbcTemplate详解(9)
    Spring 基于xml配置方式的AOP(8)
    Spring AspectJ 切入点语法详解(7)
    Spring 基于Aspectj切面表达式(6)
    spring AOP 编程--AspectJ注解方式 (4)
    Spring 切面优先级(5)
    Spring 泛型依赖注入(3)
    python反射/自省 (目前是转载)
    flask_requirements
  • 原文地址:https://www.cnblogs.com/feilongblog/p/4675471.html
Copyright © 2011-2022 走看看