标签: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