Shape案例(继承)

Shape

public abstract class Shape {
	private double area;
	private double per;
	private String color;

	public Shape() {

	}

	public Shape(String color) {
		this.color = color;

	}

	public abstract double getArea();

	public abstract double getPer();

	public abstract void showAll();

}

Rectangle

public class Rectangle extends Shape {
	private double width;
	private double height;

	public Rectangle() {

	}

	public Rectangle(double width, double height, String color) {
		super(color);
		this.width = width;
		this.height = height;

	}

	@Override
	public double getArea() {
		return width * height;
	}

	@Override
	public double getPer() {

		return 2 * (width + height);
	}

	@Override
	public void showAll() {
		System.out.println("矩形");
		System.out.println("长:" + '\t' + width);
		System.out.println("宽:" + '\t' + height);
		System.out.println("面积:" + '\t' + getArea());
		System.out.println("周长:" + '\t' + getPer());
		System.out.println("--------------------");
	}

}

Circle

public class Circle extends Shape {
	private double radius;

	public Circle() {
	}

	public Circle(double radius, String color) {
		super(color);
		this.radius = radius;
	}

	@Override
	public double getArea() {
		return 3.14 * radius * radius;
	}

	@Override
	public double getPer() {
		return 2 * 3.14 * radius;
	}

	@Override
	public void showAll() {
		System.out.println("圆");
		System.out.println("半径:" + '\t' + radius);
		System.out.println("面积:" + '\t' + getArea());
		System.out.println("周长:" + '\t' + getPer());
	}

}

Test

public class Test {
	public static void main(String[] args) {
		Shape[] shape = new Shape[2];
		Rectangle rectangle = new Rectangle(1, 2, "蓝色");
		Circle circle = new Circle(1.2, "红色");
		shape[0] = rectangle;
		shape[1] = circle;

		for (Shape shape2 : shape) {
			shape2.showAll();
		}

	}

}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值