课后第三题

3.1 设计Shape表示图形类,有面积属性area、周长属性per,颜色属性color,有两个构造方法(一个是默认的、一个是为颜色赋值的),还有3个抽象方法,分别是:getArea计算面积、getPer计算周长、showAll输出所有信息,还有一个求颜色的方法getColor。
`private double area;
private double pre;
private String color;

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

public String getColor() {
	return color;
}

public Shape() {

}

abstract void getArea();

abstract void showAll();

abstract void per();`
3.2 设计 2个子类:

3.2.1 Rectangle表示矩形类,增加两个属性,Width表示长度、height表示宽度,重写getPer、getArea和showAll三个方法,另外又增加一个构造方法(一个是默认的、一个是为高度、宽度、颜色赋值的)。

private double width;
			private double height;
			@Override
			void getArea() {
	
			System.out.println("面积为"+this.height*this.width+"颜色为"+super.getColor());	
			}
			@Override
			void showAll() {
			System.out.println("这个矩形的长为"+this.width+"这个矩形的宽"+this.height+"面积为"+this.height*this.width+"周长为"+(this.height+this.width)*2+"颜色为"+super.getColor());	
				
			}
			@Override
			void per() {
			System.out.println("这个矩形的周长为"+(this.height+this.width)*2+"颜色为"+super.getColor());
				
			}
			public Rectangle(double width, double height) {
			
				this.width = width;
				this.height = height;
			}
			public Rectangle(String color, double width, double height) {
				super(color);
				this.width = width;
				this.height = height;
			}
			public Rectangle(String color) {
				super(color);
			}
			

3.2.2 Circle表示圆类,增加1个属性,radius表示半径,重写getPer、getArea和showAll三个方法,另外又增加两个构造方法(为半径、颜色赋值的)。

private double radius;
	
	@Override
	void getArea() {
		System.out.println(3.14*radius*radius);
	}

	@Override
	void showAll() {
	System.out.println("该圆半径为"+radius);
	getArea();
	 per() ;
	}

	@Override
	void per() {
		System.out.println("该圆周长为"+6.28*radius);
		
	}

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

	public Circle(String color) {
		super(color);
	}
			

3.3 测试类中,在main方法中,声明创建每个子类的对象,并调用2个子类的showAll方法。

Shape s = new Rectangle("yellow", 10, 20);
		s.showAll();
		s.getArea();
		s.per();
		System.out.println();
		Shape s1 = new Circle("ysllow", 10);
		s1.per();
		s1.getArea();
		s1.showAll();

	}

猜你喜欢

转载自blog.csdn.net/qq_43189642/article/details/84978427