课堂练习6:
⦁ 定义一个圆类(Circle),其所在的包为bzu.info.software;定义一个圆柱类Cylinder,其所在的包为bzu.info.com;定义一个主类A,其所在的包也为bzu.info.com,在A中生成一个Cylinder对象,并输出其体积。编译并运行该类。
package bzu.info.com;
import bzu.info.software.Circle;
public class Cylinder {
double height;
Circle c;
Cylinder (double h,Circle cc){
height=h;
c=cc;
}
public double volume(){
return height*c.areas();
}
}
package bzu.info.software;
public class Circle {
double radius;
public Circle(double r){
radius=r;
}
public double areas(){
return 3.14*radius*radius;
}
}
package bzu.info.com;
import bzu.info.software.Circle;
public class A {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Circle c=new Circle(2);
Cylinder cylinder =new Cylinder(2.0,c);
System.out.println("圆柱的体积为:"+cylinder.volume());
}
}
⦁ 试着改变求体积方法的访问权限,查看并分析编译和运行结果
⦁ 把Cylinder类和A类置于不同的包中,通过对求体积方法设置不同的访问权限,查看并分析编译和运行结果
package bzu.info.software;
public class Circle {
double radius;
public Circle(double r){
radius=r;
}
public double areas(){
return 3.14*radius*radius;
}
}
package bzu.info.com;
import bzu.info.software.Circle;
public class Cylinder {
double height;
Circle c;
public Cylinder (double h,Circle cc){
height=h;
c=cc;
}
public double volume(){
return height*c.areas();
}
}
package bzu.info.hello;
import bzu.info.com.Cylinder;
import bzu.info.software.Circle;
public class A {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Circle c=new Circle(2);
Cylinder cylinder =new Cylinder(2.0,c);
System.out.println("圆柱的体积为:"+cylinder.volume());
}
}