课堂练习4:
编写代码模拟手机与SIM卡的组合关系。
要求:
SIM卡类负责创建SIM卡;
Phone类负责创建手机;
手机可以组合一个SIM卡;
手机可以更换其中的SIM卡。
public class TestPhone {
public static void main(String[] args) {
Phone phone = new Phone();
Sim sim1 = new Sim(12345);
System.out.print("号码为:"+phone.use(sim1)+"\n");
Sim sim2 = new Sim(67890);
System.out.print("更换号码为:"+phone.use(sim2));
}
}
class Phone{
long use(Sim sim1) {
Sim sim = sim1;
return sim.Sim();
}
}
class Sim{
long sim;
Sim(long number) {
sim = number;
}
long Sim() {
return sim;
}
}
课堂练习5:
public class Test {
public static void main(String[] args) {
CPU cpu = new CPU();
cpu.setSpeed(2200);
HardDisk disk = new HardDisk();
disk.setAmount(200);
PC pc = new PC();
pc.setCPU(cpu);
pc.setHardDisk(disk);
pc.show();
}
}
class PC{
CPU cpu;
HardDisk HD;
void setCPU(CPU c) {
cpu = c;
}
void setHardDisk(HardDisk h) {
HD = h;
}
void show() {
System.out.println("CPU的速度:"+cpu.getSpeed());
System.out.print("硬盘的容量:"+HD.getAmount());
}
}
class CPU{
int speed;
void setSpeed(int m) {
speed = m;
}
int getSpeed() {
return speed;
}
}
class HardDisk{
int amount;
void setAmount(int m) {
amount = m;
}
int getAmount() {
return amount;
}
}
课堂练习6:
– 定义一个圆类(Circle),其所在的包为bzu.info.software;定义一个圆柱类Cylinder,其所在的包为bzu.info.com;定义一个主类A,其所在的包也为bzu.info.com,在A中生成一个Cylinder对象,并输出其体积。编译并运行该类。
– 试着改变求体积方法的访问权限,查看并分析编译和运行结果
– 把Cylinder类和A类置于不同的包中,通过对求体积方法设置不同的访问权限,查看并分析编译和运行结果
package bzu.info.com;
import bzu.info.software.Circle;
public class A {
public static void main(String[] args) {
Circle circle = new Circle(2.0);
Cylinder cylinder = new Cylinder(3.0,circle);
System.out.println("圆柱的体积:"+cylinder.volume());
}
}
package bzu.info.com;
import bzu.info.software.Circle;
public class Cylinder {
double h;
Circle circle;
public Cylinder(double d, Circle circle2) {
h = d;
circle = circle2;
}
double volume() {
return circle.area()*h;
}
}
package bzu.info.software;
public class Circle {
double r;
public Circle(double r){
this.r = r;
}
public double area() {
double area = 3.14*r*r;
return area;
}
}
更改volume()的访问权限为public或protected,结果不受影响。更改为private,运行结果如下:
把Cylinder类和A类置于不同的包中:
当volume()访问权限为public时,成功运行。更改为protected,default或private时,结果如下: