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

[20-05-04][Thinking in Java 8]Java Polymorphism 2 - Late Binding

时间:2020-05-04 21:43:19      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:bind   ret   color   triangle   out   nbsp   ++   thinking   java   

 1 package test_1_6;
 2 
 3 public class Shape {
 4 
 5     public void draw() {
 6         
 7     }
 8     
 9     public void erase() {
10         
11     }
12 
13 }

 

package test_1_6;

public class Circle extends Shape{

    @Override
    public void draw() {
        
        System.out.println("Circle.draw()");
    }
    
    @Override
    public void erase() {
        
        System.out.println("Circle.erase()");
    }
    
}

 

 1 package test_1_6;
 2 
 3 public class Square extends Shape{
 4 
 5     @Override
 6     public void draw() {
 7 
 8         System.out.println("Square.draw()");
 9     }
10 
11     @Override
12     public void erase() {
13 
14         System.out.println("Square.erase()");
15     }
16     
17 }

 

 1 package test_1_6;
 2 
 3 public class Triangle extends Shape{
 4 
 5     @Override
 6     public void draw() {
 7 
 8         System.out.println("Triangle.draw()");
 9     }
10 
11     @Override
12     public void erase() {
13 
14         System.out.println("Triangle.erase()");
15     }
16 }

 

 1 package test_1_6;
 2 
 3 import java.util.Random;
 4 
 5 public class RandomShapeGenerator {
 6 
 7     private Random rand = new Random(47);
 8     
 9     public Shape next() {
10         switch (rand.nextInt(3)) {
11             default:
12             case 0 :
13                 return new Circle();
14             case 1 :
15                 return new Square();
16             case 2 :
17                 return new Triangle();
18         }
19     }
20 }

 

 1 package test_1_6;
 2 
 3 public class Shapes {
 4     
 5     private static RandomShapeGenerator gen = new RandomShapeGenerator();
 6 
 7     public static void main(String[] args) {
 8         
 9         Shape[] s = new Shape[9];
10         
11         for (int i = 0; i < s.length; i++) {
12             s[i] = gen.next();
13         }
14         
15         for (Shape shape : s) {
16             shape.draw();
17         }
18 
19     }
20 
21 }

 

结果如下:

Triangle.draw()
Triangle.draw()
Square.draw()
Triangle.draw()
Square.draw()
Triangle.draw()
Square.draw()
Triangle.draw()
Circle.draw()

[20-05-04][Thinking in Java 8]Java Polymorphism 2 - Late Binding

标签:bind   ret   color   triangle   out   nbsp   ++   thinking   java   

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

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