2、计算几何图形的面积和周长

来源:12-12 测评作业

mottoyin

2025-02-16

抽象类 Geometry

package com.imooc.chapter12test;

//几何抽象类
public abstract class Geometry {
    //定义抽象方法计算周长
    public abstract void calculatePerimeter();
    //定义抽象方法计算面积
    public abstract void calculateDimension();
}

圆类

package com.imooc.chapter12test;

public class Circle extends Geometry{ //圆子类继承了几何抽象类

    private double radius; //圆的半径
    private double PI = 3.14; //常量PI

    //定义构造方法,圆实例对象的初始化
    public Circle(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    //子类重写抽象方法计算周长
    @Override
    public void calculatePerimeter() {
        System.out.println("圆周长 = " + (2*PI*this.radius));
    }
	//子类重写抽象方法计算面积
    @Override
    public void calculateDimension() {
        System.out.println("圆面积 = " + (PI*this.radius*this.radius));
    }
}

矩形类

package com.imooc.chapter12test;

public class Rectangle extends Geometry {
    //定义变量长
    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;
    }

    @Override
    public void calculatePerimeter() {
        System.out.println("矩形周长 = " + 2*(length+width));
    }

    @Override
    public void calculateDimension() {
        System.out.println("矩形面积 = " + (length*width));
    }
}

测试类

package com.imooc.chapter12test;

public class GeoTest {
    public static void main(String[] args) {
        Circle c = new Circle(3.0);
        c.calculatePerimeter();
        c.calculateDimension();
        Rectangle r = new Rectangle(3.0,4.0);
        r.calculatePerimeter();
        r.calculateDimension();
    }
}

写回答

1回答

彭彭老师

2025-02-17

没有问题

0
0

Java零基础入门与实战

Java零基础入门与实战 多场景|多案例|全栈项目

318 学习 · 233 问题

查看课程