抽象类Shape及其子类

定义抽象类Shape,圆形Circle、长方形Square、Rectangle为子类。

Shape类有一个数据成员(double型),定义带参构造方法、抽象方法calArea()(返回值类型:double)在Circle、Square两个类中,实现calArea()方法。在Rectangle类中,增加一个数据成员(double型),实现calArea()方法。编写测试类:定义一个Shape类引用shape,分别指向一个Circle类、Square类、Rectangle类对象,利用多态,计算各平面图形的面积并输出。(结果保留三位小数)要求:1.数据成员全部为私有成员;2.数据从键盘输入,调用带参构造方法创建子类对象。提示:使用Math类的PI

import java.util.Scanner;
public class ShapeDemo {
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		double a,b,c,d;
		a=in.nextDouble();
		b=in.nextDouble();
		c=in.nextDouble();
		d=in.nextDouble();
		Shape sh=new Circle(a);
		System.out.printf("圆的面积:%.3f",sh.calArea());
		System.out.println();
		sh=new Square(b);
		System.out.printf("正方形的面积:%.3f",sh.calArea());
		System.out.println();
		sh=new Rectangle(c,d);
		System.out.printf("矩形的面积:%.3f",sh.calArea());
		in.close();
	}

}
abstract class Shape
{
	private double a;
	public Shape()
	{
		a=0;
	}
	public Shape(double a)
	{
		this.a=a;
	}
	abstract double calArea();
	public double getA() {
		return a;
	}
	public void setA(double a) {
		this.a = a;
	}
}
class Circle extends Shape
{
	public Circle(double a)
	{
		super(a);
	}
	double calArea() {
		return getA()*getA()*Math.PI;
	}
	
}
class Square extends Shape
{
	public Square(double a)
	{
		super(a);
	}
	double calArea() {
		return getA()*getA();
	}
	
}
class Rectangle extends Shape
{
	private double b;
	public Rectangle(double a,double b)
	{
		super(a);
		this.b=b;
	}
	double calArea() {
		return getA()*b;
	}
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学工科的皮皮志^_^

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值