view plaincopy to clipboardPRint? package cn.edu.uibe.poly;
public class Shape { public void draw(){ System.out.println("Shape.draw()"); }
} package cn.edu.uibe.poly;
public class Shape { public void draw(){ System.out.println("Shape.draw()"); }
}
Rectangle类是Shape类的一个子类
view plaincopy to clipboardprint? package cn.edu.uibe.poly; public class Rectangle extends Shape { @Override public void draw() { System.out.println("画矩形"); }
} package cn.edu.uibe.poly; public class Rectangle extends Shape { @Override public void draw() { System.out.println("画矩形"); }
}
Circle类也是Shape类的子类
view plaincopy to clipboardprint? package cn.edu.uibe.poly; public class Circle extends Shape{ @Override public void draw() { System.out.println("画圆"); } } package cn.edu.uibe.poly; public class Circle extends Shape{ @Override public void draw() { System.out.println("画圆"); } }
Triangle类是Shape类的另外一个子类
view plaincopy to clipboardprint? package cn.edu.uibe.poly; public class Triangle extends Shape{ @Override public void draw() { System.out.println("画三角形"); } } package cn.edu.uibe.poly; public class Triangle extends Shape{ @Override public void draw() { System.out.println("画三角形"); } }
ShapeDemo类中随机生成矩形、圆、三角形,然后用Shape类型的引用调用。
view plaincopy to clipboardprint? package cn.edu.uibe.poly; import java.util.*; public class ShapeDemo { Random rand = new Random(); public Shape createShape(){ int c = rand.nextInt(3); Shape s = null; switch(c){ case 0: s = new Rectangle(); break; case 1: s = new Circle(); break; case 2: s = new Triangle(); break; } return s; } public static void main(String[] args) { ShapeDemo demo = new ShapeDemo(); Shape[] shapes = new Shape[10]; for(int i=0;i<shapes.length;i++){ shapes[i] = demo.createShape(); } for(int i=0;i<shapes.length;i++){ shapes[i].draw();//同样的消息,不同的响应 }
}
} package cn.edu.uibe.poly; import java.util.*; public class ShapeDemo { Random rand = new Random(); public Shape createShape(){ int c = rand.nextInt(3); Shape s = null; switch(c){ case 0: s = new Rectangle(); break; case 1: s = new Circle(); break; case 2: s = new Triangle(); break; } return s; } public static void main(String[] args) { ShapeDemo demo = new ShapeDemo(); Shape[] shapes = new Shape[10]; for(int i=0;i<shapes.length;i++){ shapes[i] = demo.createShape(); } for(int i=0;i<shapes.length;i++){ shapes[i].draw();//同样的消息,不同的响应 }