编写代码模拟手机与SIM卡的组合关系。
要求:
SIM卡类负责创建SIM卡;
Phone类负责创建手机;
手机可以组合一个SIM卡;
手机可以更换其中的SIM卡。
代码:
SIM类:
public class Sim {
long num;
Sim(long num)
{
this.num=num;
}
long getNum()
{
return num;
}
}
PHONE类:
public class Phone {
Sim sim;
void setSim(Sim sim)
{
this.sim=sim;
}
long seeNum()
{
return sim.getNum();
}
}
测试:
public class testPhone {
public static void main(String[] args) {
Phone phone=new Phone();
Sim sim=new Sim(15126354);
phone.setSim(sim);
System.out.println("原手机号为"+phone.seeNum());
Sim sim1=new Sim(1216374);
phone.setSim(sim1);
System.out.println("更改后手机号为:"+phone.seeNum());
}
}
代码结果:
课堂练习5:
代码
cpu类:
public class Cpu {
int speed;
void setSpeed(int speed){
this.speed=speed;
}
int getSpeed()
{
return speed;
}
}
HardDisk类:
public class HardDisk {
int amount;
void setAmount(int amount){
this.amount=amount;
}
int getAmount()
{
return amount;
}
}
pc类:
public class Pc {
Cpu cpu;
HardDisk hd;
void setCpu(Cpu cpu){
this.cpu=cpu;
}
void setHardDisk(HardDisk hd){
this.hd=hd;
}
void show(){
System.out.println("CPU速度为:"+cpu.getSpeed());
System.out.println("硬盘容量为:"+hd.getAmount());
}
}
测试:
public class TestPc {
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();
}
}
测试结果:
课堂练习6:
– 定义一个圆类(Circle),其所在的包为bzu.info.software;定义一个圆柱类Cylinder,其所在的包为bzu.info.com;定义一个主类A,其所在的包也为bzu.info.com,在A中生成一个Cylinder对象,并输出其体积。编译并运行该类。
– 试着改变求体积方法的访问权限,查看并分析编译和运行结果
– 把Cylinder类和A类置于不同的包中,通过对求体积方法设置不同的访问权限,查看并分析编译和运行结果
bzu.info.software包中Circle类:
package bzu.info.software;
public class Circle {
double radius,area;
public Circle(double r){
radius =r;
}
public void setRadius(double r){
radius=r;
}
public double getRadius(){
return radius;
}
public double getArea(){
area=3.14*radius*radius;
return area;
}
}
bzu.info.com包中Cylinder类:
package bzu.info.com;
import bzu.info.software.Circle;
public class Cylinder {
Circle bottom;
double height;
double volume;
Cylinder(Circle b,double h){
bottom=b;
height=h;
}
double getVolume(){
volume=bottom.getArea()*height;
return volume;
}
double getBottomRadius(){
return bottom.getRadius();
}
}
package bzu.info.com;
import bzu.info.software.Circle;
public class A {
public static void main(String[] args) {
Circle circle=new Circle(1);
Cylinder cylinder=new Cylinder(circle,5);
System.out.println("圆柱半径:"+cylinder.getBottomRadius()+"圆柱高:"+cylinder.height+"圆柱体积:"+cylinder.getVolume());
}
}
反思: