7-11 Abstract and Shape(分数 5)
我们有抽象类Shape,它有抽象方法getArea,类Circle和Rectangle将从Shape继承,请阅读并完成如下代码:
题意:抽象类Shape含有抽象方法getArea,Circle类与Rectangle类为Shape子类,补全如下代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int radius = input.nextInt();
int height = input.nextInt();
int width = input.nextInt();
//to create an Shape Array whose length is 2
Shape[] shapes =【】;
//shapes[0] refer to a Circle object
shapes[0] =【】;
//shapes[1] refer to a Rectangle object
shapes[1] = 【】;
//call getArea method with shapes
for(int i =0;i<shapes.length;i++)
System.out.printf("the area of shape :%.2f\n",【】);
}
}
//to declare abstract class
【】 Shape{
//to declare abstract method double getArea();
【】
}
class Circle 【】{
private int radius;
//override method getArea
【】
public Circle(int radius) {
super();
this.radius = radius;
}
}
class Rectangle 【】{
private int height,width;
//override method getArea
【】
public Rectangle(int height, int width) {
super();
this.height = height;
this.width = width;
}
}
请在这里写题目描述。例如:本题目要求读入2个整数A和B,然后输出它们的和。
输入格式:
input radius , height and width at a line.
输出格式:
output the area of circle and rectangle object at different lines.
输入样例:
在这里给出一组输入。例如:
4 5 6
输出样例:
在这里给出相应的输出。例如:
the area of shape :50.27
the area of shape :30.00
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int radius = input.nextInt();
int height = input.nextInt();
int width = input.nextInt();
//定义Shape类数组长度为2
Shape[] shapes = new Shape[2];
//shapes[0]为Circle类
shapes[0] = new Circle(radius);
//shapes[1]为Rectangle类
shapes[1] = new Rectangle(height,width);
//遍历数组调用getArea方法
for(int i =0;i<shapes.length;i++)
System.out.printf("the area of shape :%.2f\n",shapes[i].getArea());
}
}
//定义抽象类
abstract class Shape{
//定义抽象方法
abstract public double getArea();
}
class Circle extends Shape {
private int radius;
//重写getArea方法
public double getArea() {
return Math.PI*radius*radius;
}
public Circle(int radius) {
super();
this.radius = radius;
}
}
class Rectangle extends Shape {
private int height,width;
//重写getArea方法
public double getArea() {
return height*width;
}
public Rectangle(int height, int width) {
super();
this.height = height;
this.width = width;
}
}