码迷,mamicode.com
首页 > 编程语言 > 详细

[20-05-05][Thinking in Java 9]Java Polymorphism 3 - Extensibility

时间:2020-05-05 10:34:38      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:default   i++   and   run   public   use   code   end   int   

 1 package test_2_1;
 2 
 3 public class Rodent {
 4 
 5     public void eat() {
 6         
 7         System.out.println("Rodent.eat()");
 8     }
 9     
10     public void run() {
11         
12         System.out.println("Rodent.run()");
13     }
14 }

 

 1 package test_2_1;
 2 
 3 public class Mouse extends Rodent{
 4 
 5     @Override
 6     public void eat() {
 7         
 8         System.out.println("Mouse.eat()");
 9     }
10     
11     @Override
12     public void run() {
13         
14         System.out.println("Monse.run()");
15     }
16 }

 

 1 package test_2_1;
 2 
 3 public class Gerbil extends Rodent{
 4 
 5     @Override
 6     public void eat() {
 7         
 8         System.out.println("Gerbil.eat()");
 9     }
10 }

 

 1 package test_2_1;
 2 
 3 public class Hamster extends Rodent{
 4 
 5     @Override
 6     public void eat() {
 7         
 8         System.out.println("Hamster.eat()");
 9     }
10 }

 

 1 package test_2_1;
 2 
 3 import java.util.Random;
 4 
 5 public class RandomRodent {
 6 
 7     private Random random = new Random(50);
 8     
 9     public Rodent getRandomRodent() {
10         switch (random.nextInt(3)) {
11             default:
12             case 0:
13             return new Mouse();
14             case 1:
15             return new Gerbil();
16             case 2:
17             return new Hamster();
18         }
19     }
20 }

 

 1 package test_2_1;
 2 
 3 public class Test {
 4     
 5     private static RandomRodent rr = new RandomRodent();
 6 
 7     public static void main(String[] args) {
 8 
 9         Rodent[] rodents = new Rodent[5];
10         
11         for (int i = 0; i < rodents.length; i++) {
12             rodents[i] = rr.getRandomRodent();
13         }
14         
15         for (Rodent rodent : rodents) {
16             rodent.eat();
17         }
18     }
19 
20 }

 

结果如下:

Gerbil.eat()
Mouse.eat()
Hamster.eat()
Gerbil.eat()
Gerbil.eat()

[20-05-05][Thinking in Java 9]Java Polymorphism 3 - Extensibility

标签:default   i++   and   run   public   use   code   end   int   

原文地址:https://www.cnblogs.com/mirai3usi9/p/12829647.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!