实验 (3) 项目名称:类与对象-类封装对象的属性和功能
一、 实验报告内容一般包括以下几个内容:
- 实验项目名称 实验3 类与对象-类封装对象的属性和功能
- 实验目的和要求
本实验的目的:
(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) - 实验原理
- 主要仪器设备
(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());
}
}