java开发实战经典(第二版)P217 6-5

6.5   定义类shape,用来表示一般二维图形。shape具有抽象方法area和perimeter,分别用来计算形状的面积和周长。试定义一些二维形状类(如矩形、三角形、圆形、椭圆形等),这些类均为shape的子类。

package book;

abstract class Shape {
	public abstract double area();

	public abstract double perimeter();
}

class Rectangle extends Shape { // 矩形
	private double wide; // 宽
	private double longs; // 长

	public Rectangle() {
	}

	public Rectangle(double wide, double longs) {
		super();
		this.wide = wide;
		this.longs = longs;
	}

	public void setWide(double wide) {
		this.wide = wide;
	}

	public double getWide() {
		return wide;
	}

	public void setLongs(double longs) {
		this.longs = longs;
	}

	public double longs() {
		return longs;
	}

	public double area() {
		return this.longs * this.wide;
	}

	public double perimeter() {
		return (this.longs + this.wide) * 2;
	}
}

class Triangle extends Shape { // 三角形
	private double edgea;
	private double edgeb;
	private double edgec;

	public Triangle() {
	}

	public Triangle(double edgea, double edgeb, double edgec) {
		super();
		this.edgea = edgea;
		this.edgeb = edgeb;
		this.edgec = edgec;
	}

	public double area() {
		return this.edgea * this.edgeb / 2;
	}

	public double perimeter() {
		return this.edgea + this.edgeb + this.edgec;
	}

	public void setEdgea(double edgea) {
		this.edgea = edgea;
	}

	public double getEdgea() {
		return edgea;
	}

	public void setEdgeb(double edgeb) {
		this.edgeb = edgeb;
	}

	public double getEdgeb() {
		return edgeb;
	}

	public void setEdgec(double edgec) {
		this.edgec = edgec;
	}

	public double getEdgec() {
		return edgec;
	}
}

class Round extends Shape {
	private double radius;

	public Round() {
	}

	public Round(double radius) {
		super();
		this.radius = radius;
	}

	public double area() {
		return this.radius * this.radius * Math.PI;
	}

	public double perimeter() {
		return this.radius * 2 * Math.PI;
	}

	public void setRadius(double radius) {
		this.radius = radius;
	}

	public double getRadius() {
		return radius;
	}
}

public class JiOu {
	public static void main(String[] args) {
		Shape rectangle = new Rectangle(10.5, 20.6);
		Shape triangle = new Triangle(10.1, 20.2, 30.3);
		Shape round = new Round(30.3);
		System.out.println("矩形面积:" + rectangle.area() + ",矩形周长:" + rectangle.perimeter());
		System.out.println("三角形面积:" + triangle.area() + ",三角形周长:" + triangle.perimeter());
		System.out.println("圆形面积:" + round.area() + ",圆形周长:" + round.perimeter());
	}
}

运行结果:

矩形面积:216.3,矩形周长:62.2
三角形面积:102.00999999999999,三角形周长:60.599999999999994
圆形面积:2884.2647993342534,圆形周长:190.38051480754146

 

你可能感兴趣的:(java开发实战经典(第二版))