定义三个类,父类(抽象类)GeometricObject代表几何形状,子类Circle代表圆形,子类Rectangle代表矩形。具体属性和方法如下:
父类 (抽象类)GeometricObject
属性:private String color; private String name;
为上述变量提供getter()和setter()方法
构造方法:为color和name初始化
public GeometricObject(String color, String name)
抽象方法:
public double findArea();用于计算几何图形的面积
子类:Circle
属性:private double radius;
为上述变量提供getter()和setter()方法
构造方法:
设计构造方法为圆形的name,color和radius初始化
方法:
实现findArea()方法用于计算圆形的面积并返回计算结果
子类:Rectangle
属性:private double width; private double height;
为上述变量提供getter()和setter()方法
构造方法:
设计构造方法为圆形的name,color,width和height初始化
方法:
实现findArea()方法用于计算矩形的面积并返回计算结果
测试类Main
方法:
public static void main(String[] args) {
String shape;
String color;
double r,w,h;
//System.out.println("input color,shape:");
Scanner sc=new Scanner(System.in);
color=sc.nextLine();
shape=sc.nextLine();
GeometricObject g=null;
//输入颜色、形状,根据形状的不同 再输入半径或宽高、创建不同的对象,计算面积及输出
/* */
}
public static void show(GeometricObject g){//该函数的方法体固定如下:
System.out.println(g.getName()+"的颜色是:"+g.getColor()+",面积是:"+g.findArea());
}
注意:须书写抽象类GeometricObject、子类Circle和Rectangle。
输入格式:
蓝色
圆形
3.4
输出格式:
圆形的颜色是:蓝色,面积是:36.31681107549801
输入样例:
在这里给出一组输入。例如:
红色
矩形
1 2
输出样例:
在这里给出相应的输出。例如:
矩形的颜色是:红色,面积是:2.0
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
答案
import java.util.Scanner;
import static java.lang.Math.PI;
public class Main {
public static void main(String[] args) {
String shape;
String color;
double r,w,h;
Scanner sc=new Scanner(System.in);
color=sc.nextLine();
shape=sc.nextLine();
GeometricObject g=null;
if(shape.equals("圆形"))
{
r=sc.nextDouble();
Circle c=new Circle(color,"圆形",r);
show(c);
}
else {
w=sc.nextDouble();
h=sc.nextDouble();
Rectangle rc=new Rectangle(color,"矩形",w,h);
show(rc);
}
}
public static void show(GeometricObject g){//该函数的方法体固定如下:
System.out.println(g.getName()+"的颜色是:"+g.getColor()+",面积是:"+g.findArea());
}
}
abstract class GeometricObject
{
public abstract String getName();
public abstract String getColor();
public abstract double findArea();
}
class Circle extends GeometricObject
{
String color,name;
double r;
public Circle(String color, String name,double r) {
this.color=color;
this.name=name;
this.r=r;
}
public String getName() {
return name;
}
public String getColor() {
return color;
}
public double findArea() {
return r*r*PI;
}
}
class Rectangle extends GeometricObject {
String color,name;
double w,h;
public Rectangle(String color, String name,double w,double h) {
this.color=color;
this.h=h;
this.w=w;
this.name=name;
}
public String getName() {
return name;
}
public String getColor() {
return color;
}
public double findArea() {
return w*h;
}
}