抽象类

Description
先定义一个抽象Graphic类,有求面积的computeArea抽象方法(返回值为面积,圆周率取3.14);
然后定义一个从Graphic派生的Circle类,有double类型的半径,以及重写的computeArea抽象方法。
再定义一个从Graphic派生的Rectangle类,有double类型的长和宽属性,以及重写的computeArea抽象方法。
要求main方法中至少包含如下代码(这些语句不要求必须放在一起):
Graphic g;
g=new Circle®;
g=new Rectangle(a,b);
g.computeArea();

Input
第一行输入数据的组数N,然后有N组数据。每组数据由一个字符和几个浮点数组成,第一个如何是’c’表示Circle,是’r’表示Rectangle;如果前面是’c’,后面跟一个浮点,如果是’r’后面跟两个浮点。
Output
图形类型及其面积(精度保留2位)。
Sample Input
4
c 10
r 20 10
r 5 4
c 20

Sample Output
Circle:314.00
Rectangle:200.00
Rectangle:20.00
Circle:1256.00

import java.util.*;
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
int n;
Scanner in=new Scanner (System.in);
n=in.nextInt();
Graphic g ;
int i=0;
do
{i++;
char f;
f=in.next().charAt(0);
if(f=='r')
{float a=in.nextFloat();
float b=in.nextFloat();
	g=new Rectangle(a,b);
	g.computeArea();
}
if(f=='c')
{
float r=in.nextFloat();
 g=new Circle(r);
 g.computeArea();
}
}
while(i<n);
	}
}
abstract class Graphic
{
	public abstract void computeArea();
}
class Circle extends Graphic
{
	private double radius;
	public Circle(double radius)
	{
		this.radius=radius;
	}
	public void  computeArea()
	{
		System.out.printf("Circle:%.2f\n",radius*radius*3.14);
	}
}
class Rectangle extends Graphic
{
	double length;
	private double width;
	public Rectangle(double length,double width)
	{
		this.length=length;
		this.width=width;
	}
	public void computeArea()
	{
		System.out.printf("Rectangle:%.2f\n",length*width);
	}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不关我事~

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

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

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

打赏作者

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

抵扣说明:

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

余额充值