Java上机实验报告(3)

实验 (3) 项目名称:类与对象-类封装对象的属性和功能

一、 实验报告内容一般包括以下几个内容:

  1. 实验项目名称 实验3 类与对象-类封装对象的属性和功能
  2. 实验目的和要求
    本实验的目的:
    (1) 学会使用类来封装对象的属性和功能
    (2)掌握类变量与实例变量,以及类方法与实例方法的区别
    (3)掌握构造方法和一般的方法的区别
    实验具体要求:
    定义一个圆柱体类Cylinder,类中含有方法area()求面积,方法volume ()计算体积。然后在主类E中用Cylinder创建相应的对象cylinder调用类中的成员变量和方法,然后计算圆柱体的底面积与体积。
    请用3个不同的方法求解该问题:(分别写3个不同的程序)
    方法1:主类中第一行代码是 (程序的主类E1)
    Cylinder cylinder=new Cylinder();
    方法2:主类中第一行代码是(程序的主类E2)
    Cylinder cylinder=new Cylinder(a,b); //a是输入的参数半径radius,b是输入的高height.
    方法3:要求增加两个类Area,和Volumn分别用来计算面积和体积。在主类中用Cylinder调用Area和Volumn分别计算面积和体积。(程序的主类E3)
  3. 实验原理
  4. 主要仪器设备
    (1)学生每人一台PC机;
    (2)互联网环境。

实验解答:
Cylinder.java

package data20240314;

public class Cylinder
{
    double radius;
    double height;
    Cylinder() {
        radius = 1.0;
        height = 1.0;
    }
    Cylinder(double radius,double height) {
        this.radius = radius;
        this.height = height;
    }
    double area() {
        return Math.PI * Math.pow(radius,2);
    }
    double volume() {
        return Math.PI * Math.pow(radius,2) * height;
    }
    double area1() {
        Area area = new Area();
        return area.area(radius);
    }
    double volumn() {
        Volumn volumn = new Volumn();
        return volumn.volumn(radius,height);
    }
}

E1.java

package data20240314;

public class E1 {
    public static void main(String[] args) {
        Cylinder cylinder = new Cylinder();
        System.out.printf("圆柱体的底面积为:%.2f\n",cylinder.area());
        System.out.printf("圆柱体的体积为:%.2f\n",cylinder.volume());
    }
}

E2.java

package data20240314;

public class E2 {
    public static void main(String[] args) {
        Cylinder cylinder = new Cylinder(2.0,2.0);
        System.out.printf("圆柱体的底面积为:%.2f\n",cylinder.area());
        System.out.printf("圆柱体的体积为:%.2f\n",cylinder.volume());
    }
}

Area.java

package data20240314;

public class Area {
    double area(double radius)
    {
        return Math.PI * Math.pow(radius,2);
    }
}

Volumn.java

package data20240314;

public class Volumn {
    double volumn(double radius,double height)
    {
        return Math.PI * Math.pow(radius,2) * height;
    }
}

E3.java

package data20240314;

public class E3 {
    public static void main(String[] args) {
        Cylinder cylinder = new Cylinder();
        System.out.printf("圆柱体的底面积为:%.2f\n",cylinder.area1());
        System.out.printf("圆柱体的体积为:%.2f\n",cylinder.volumn());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值