关于java多态的列子程序如下:
import java.util.*;
class Shape {
public void draw() {}
public void erase() {}
public void amend() {System.out.println("sdafosrk");}
}
class Circle extends Shape {
public void draw() { System.out.println("Circle.draw()"); }
public void erase() { System.out.println("Circle.erase()"); }
public void amend() { System.out.println("Circle.amend()"); }
}
class Triangle extends Shape {
public void draw() { System.out.println("Circle.draw()"); }
public void erase() { System.out.println("Circle.erase()"); }
public void amend() { System.out.println("Circle.amend()"); }
}
class Square extends Shape {
public void draw() { System.out.println("Circle.draw()"); }
public void erase() { System.out.println("Circle.erase()"); }
public void amend() { System.out.println("Circle.amend()"); }
}
class RandomShapeGenerator {
public Random rand = new Random(47);
public Shape next() {
switch(rand.nextInt(3)) {
default:
case 0: return new Circle();
case 1: return new Square();
case 2: return new Triangle();
}
}
}
public class Sha {
private static RandomShapeGenerator gen = new RandomShapeGenerator();
public static void main(String[] args) {
Shape[] s = new Shape[10];
for(int i = 0; i < s.length; i++)
s[i] = gen.next();
for(Shape shp : s) {
shp.draw();
shp.erase();
shp.amend();
}
}
}