类的基本操作(Java小作业):圆类、矩形类

 Java作业,类的相关操作:定义圆类、矩形类,并实例化对象

import java.util.Scanner;

//圆类
class Circle {

    //定义圆类的私有属性radius
    private float radius;

    //无参构造方法
    Circle() {
        radius = 0;
    }

    //带参构造方法
    Circle(float radius) {
        this.radius = radius;
    }

    //获取radius的值并返回
    public float getRadius() {
        return radius;
    }

    //修改私有属性radius的值
    public void setRadius(float radius) {
        this.radius = radius;
    }

    //计算圆的面积并返回
    public double getArea() {
        return radius * radius * Math.PI;
    }

    //计算圆的周长并返回
    public double getPerimeter() {
        return radius * Math.PI * 2;
    }

}

//矩形类
class Rectangle {

    //定义矩形类的私有属性:长和宽
    private float length;
    private float width;

    //无参构造方法
    Rectangle() {
        length = 0;
        width = 0;
    }

    //带参构造方法
    Rectangle(float length, float width) {
        this.length = length;
        this.width = width;
    }

    //获取length的值并返回
    public float getLength() {
        return length;
    }

    //修改私有属性length的值
    public void setLength(float length) {
        this.length = length;
    }

    //获取width的值并返回
    public float getWidth() {
        return width;
    }

    //修改私有属性width的值
    public void setWidth(float width) {
        this.width = width;
    }

    //计算矩形的面积并返回
    public double getArea() {
        return width * length;
    }

    //计算矩形的周长并返回
    public double getPerimeter() {
        return (width + length) * 2;
    }

}

//测试类
public class Graph {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        //圆类实例化
        Circle c = new Circle();
        //调用类的成员方法 setRadius 修改半径 radius 的值
        System.out.println("\n请输入圆的半径:");
        c.setRadius(sc.nextFloat());
        System.out.println("半径为:" + c.getRadius() + "的圆的面积为:" + c.getArea());
        System.out.println("半径为:" + c.getRadius() + "的圆的周长为:" + c.getPerimeter());

        //矩形类实例化
        Rectangle r = new Rectangle();
        //调用 set 方法修改矩形长和宽的值
        System.out.print("\n请输入矩形的长:");
        r.setLength(sc.nextFloat());
        System.out.print("请输入矩形的宽:");
        r.setWidth(sc.nextFloat());
        System.out.println("长为" + r.getLength() + "宽为" + r.getWidth() + "的矩形的面积为:" + r.getArea());
        System.out.println("长为" + r.getLength() + "宽为" + r.getWidth() + "的矩形的周长为:" + r.getPerimeter());
    }
}

  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值