Java面向对象练习(2) (2024.7.11)

        圆类

package area20240711;

public class Circle extends Picture{
    private double r;
    private final double PI = 3.1415926;

    public Circle(){}

    public Circle(double r) {
        this.r = r;
    }

    public double getR() {
        return r;
    }

    public void setR(double r) {
        this.r = r;
    }

    public double getPI() {
        return PI;
    }

    @Override
    public double length() {
        return 2 * PI * this.r;
    }

    @Override
    public double area() {
        return this.r * this.r * PI;
    }
}

        图形类

package area20240711;

public abstract class Picture {
    public abstract double length();
    public abstract double area();
}

        矩形类

package area20240711;

public class Rectangle extends Picture{
    private double length;
    private double width;

    public Rectangle(){}

    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 double length() {
        return 2.0 * (this.length + this.width);
    }

    @Override
    public double area() {
        return this.length * this.width * 1.0;
    }
}

        测试

package area20240711;
import java.util.Scanner;
public class AreaTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 创建一个矩形
        Rectangle rtg = creatRectangle();
        System.out.println("长为" + rtg.getLength() + "宽为" + rtg.getWidth()
        + "的矩形的周长是" + rtg.length());
        System.out.println("长为" + rtg.getLength() + "宽为" + rtg.getWidth()
        + "的矩形的面积是" + rtg.area());

        // 创建一个圆形
        Circle c = creatCircle();
        System.out.println("半径为" + c.getR() + "圆的周长是" + c.length());
        System.out.println("半径为" + c.getR() + "圆的面积是" + c.area());


    }

    public static Rectangle creatRectangle () {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入矩形的长");
        double length = sc.nextDouble();
        System.out.println("请输入矩形的宽");
        double width = sc.nextDouble();
        return new Rectangle(length, width);
    }

    public static Circle creatCircle() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入圆形的半径");
        double r = sc.nextDouble();
        return new Circle(r);
    }
}

 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值