水文
主要: 抽象类和抽象方法的实现
作业内容要求:
1、定义Shape(形状)类,包含:计算面积的抽象方法getArea();
2、定义Rectangle(矩形)类,继承Shape类,实现getArea()方法;
3、定义Circle(圆)类,继承Shape类,实现getArea()方法;
4、编写测试类,创建Rectangle和Circle对象,并调用getArea方法计算面积并输出。
可能的Java代码:
import java.util.*;
//抽象类
abstract class Shape
{
public abstract Double calculateShape();
}
//Rectangle类
class Rectangle extends Shape
{
private double length;
private double width;
public Rectangle(double length, double width)
{
this.length = length;
this.width = width;
}
public double getLength()
{
return length;
}public void setLength(double length)
{
this.length = length;
}
public double getWidth()
{
return width;
}public void setWidth(double width)
{
this.width = width;
}
//继承Shape类,实现getArea()方法
public Double getArea()
{
return width*length;
}
}
// Circle类
class Circle extends Shape
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public double getRadius()
{
return radius;
}
public void setR(double radius)
{
this.radius = radius;
}
//继承Shape类,实现getArea()方法
public Double getArea()
{
return Math.PI*radius*radius;
}
}
class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
double radius=sc.nextDouble();
Circle circle=new Circle(radius);
System.out.println("半径为:"+circle.getRadius()+"的圆面积为:"+circle.getArea());
double width=sc.nextDouble();
double length=sc.nextDouble();
Rectangle rectangle=new Rectangle(width,length);
System.out.println("长为:"+rectangle.getLength()+"宽为:"+rectangle.getArea()+"的长方形面积为:"+rectangle.calculateShape());
}
}
样例运行结果:
END