上机练习2 类与对象
程序员文章站
2022-03-06 11:06:15
...
课堂练习4:
编写代码模拟手机与SIM卡的组合关系。
要求:
SIM卡类负责创建SIM卡;
Phone类负责创建手机;
手机可以组合一个SIM卡;
手机可以更换其中的SIM卡。
package PhoneSim;
public class SIM {
private int sNum; //卡号
public int getsNum() {
return sNum;
}
public void setsNum(int sNum) {
this.sNum = sNum;
}
}
package PhoneSim;
public class Phone {
private SIM pSIM; //手机卡
public SIM getpSIM() {
return pSIM;
}
public void setpSIM(SIM pSIM) {
this.pSIM = pSIM;
}
}
package PhoneSim;
public class TestMobileSIM {
public static void main(String args[]) {
Phone phone = new Phone();
SIM simOne = new SIM();
SIM simTwo = new SIM();
simOne.setsNum(1234);
simTwo.setsNum(9876);
phone.setpSIM(simOne);
System.out.println("手机卡号为:"+phone.getpSIM().getsNum());
phone.setpSIM(simTwo);
System.out.println("更换手机卡号为:"+phone.getpSIM().getsNum());
}
}
课堂练习5:
package test;
public class CPU {
int speed;
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
}
package test;
public class HardDisk {
int amount;
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
package test;
public class PC {
CPU cpu;
HardDisk HD;
public void setCpu(CPU cpu) {
this.cpu = cpu;
}
public void setHD(HardDisk hD) {
HD = hD;
}
public void show(){
System.out.println("CPU is "+cpu.getSpeed());
System.out.println("HD is "+HD.getAmount());
}
}
package test;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
CPU cpu= new CPU();
cpu.setSpeed(2200);
HardDisk disk=new HardDisk();
disk.setAmount(200);
PC pc=new PC();
pc.setCpu(cpu);
pc.setHD(disk);
pc.show();
}
}
上一篇: 写代码爬取了某 Hub 资源,只为撸这个鉴黄平台!
下一篇: 对象与类(二)