package com.lovo;
/**
* 图形类(父类)
* @author 周博
*/
import java.awt.Color;
import java.awt.Graphics;
//如果一个类有抽象方法,这个类必须被声明为抽象类
//抽象类不能实例化(不能创建对象),抽象类是专门用来被继承的;
public abstract class Shape {
protected int x, y;
protected Color color;
/**
* 无参构造器
*/
public Shape(){
}
/**
* 计算周长
* @return 图形的周长
*/
public abstract double getCircumfefence(); //抽象方法,没有实现 关键字:abstract
/**
* 计算面积
* @return图形的面积
*/
public abstract double getArea();
/**
* 绘画
* @param g 画笔
*/
public abstract void draw(Graphics g);
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}
package com.lovo;
import java.awt.Graphics;
public class Rectangle extends Shape {
private int width, height;
/**
* 构造器
* @param w
* @param h
*/
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public double getCircumfefence() {
return 2 * (width + height);
}
@Override
public double getArea() {
return width* height;
}
@Override
public void draw(Graphics g) {
g.setColor(color);
g.drawOval(x, y, width, height);
}
}
package com.lovo;
import java.awt.Graphics;
public class Circle extends Shape {
private int radius;
public Circle(int radius){
this.radius = radius;
}
@Override
public double getCircumfefence() {
return 2 * Math.PI * radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public void draw(Graphics g) {
g.setColor(color);
g.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
}
}
package com.lovo;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Polymorphism extends JFrame {
private Shape[] shapes = new Shape[5];
public Polymorphism(){
this.setSize(800, 800);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
for(int i = 0; i < shapes.length; i ++){
int num = (int) (Math.random() * 2);
Shape currentShape = null;
switch(num){
case 0:
int ridius = (int) (Math.random() * 50 + 50);
currentShape = new Circle(ridius);
break;
case 1:
int width = (int) (Math.random() * 300 + 100);
int height = (int) (Math.random() * 300 + 100);
currentShape = new Rectangle(width,height);
break;
}
int red = (int) (Math.random() * 256);
int greed = (int) (Math.random() * 256);
int blue = (int) (Math.random() * 256);
currentShape.setColor(new Color(red, greed, blue));
int x = (int) (Math.random() * 300 + 100);
int y = (int) (Math.random() * 300 + 100);
currentShape.setX(x);
currentShape.setY(y);
shapes[i] = currentShape;
}
}
public void paint(Graphics g){
super.paint(g);
// for-e 循环打印
for(Shape sh :shapes ){
sh.draw(g);
}
}
public static void main(String[] args) {
new Polymorphism().setVisible(true);
}
}