面向对象与Java程序设计基础题目:设计一个程序可以一计算平面图形的面积和立体图形的体积。1.使用interface关键

1个回答

  • 1.shape接口:

    public interface Shape {

    double getArea();

    }

    2.shape2D接口:

    public interface Shape2D extends Shape {

    double getCircumference();

    }

    shape3D接口:

    public interface Shape3D extends Shape {

    double getVolume();

    }

    3.Circle类:

    public class Circle implements Shape2D {

    public Circle(double radius){

    this.setRadius(radius);

    }

    @Override

    public double getCircumference() {

    return 2*Math.PI*radius;

    }

    @Override

    public double getArea() {

    return Math.PI*radius*radius;

    }

    public void setRadius(double radius) {

    this.radius = radius;

    }

    public double getRadius() {

    return radius;

    }

    private double radius;

    }

    4.Square类:

    public class Square implements Shape3D {

    public Square(int length,int width,int height){

    this.setHeight(height);

    this.setLength(length);

    this.setWidth(width);

    }

    @Override

    public double getVolume() {

    return length*width*height;

    }

    @Override

    public double getArea() {

    return 2*length*width+2*width*height+2*length*height;

    }

    public int getLength() {

    return length;

    }

    public void setLength(int length) {

    this.length = length;

    }

    public int getWidth() {

    return width;

    }

    public void setWidth(int width) {

    this.width = width;

    }

    public int getHeight() {

    return height;

    }

    public void setHeight(int height) {

    this.height = height;

    }

    private int length;

    private int width;

    private int height;

    }

    5.Scaleable接口:

    public interface Scableable {

    void scale(double propertion);

    }

    6.CircleScaleable类:

    public class CircleScaleable extends Circle implements Scableable {

    public CircleScaleable(int radius) {

    super(radius);

    }

    @Override

    public void scale(double propertion) {

    super.setRadius(super.getRadius()*propertion);

    }

    }

    7.CircleScaleable测试程序:

    public class CircleScaleableTest {

    public static void main(String[] args){

    CircleScaleable circle=new CircleScaleable(100);

    printShape2D(circle);

    circle.scale(0.5);

    printShape2D(circle);

    circle.scale(2.5);

    printShape2D(circle);

    }

    public static void printShape2D(Shape2D shape){

    System.out.println("##############n");

    System.out.println("Circumference:"+shape.getCircumference());

    System.out.println("Area:"+shape.getArea()+"n");

    }

    }