Part 3 对象的组合

Part 3 对象的组合

课堂练习4

编写代码模拟手机与SIM卡的组合关系。

要求:

           SIM卡类负责创建SIM卡;

           Phone类负责创建手机;

          手机可以组合一个SIM卡;

          手机可以更换其中的SIM卡。


实现代码:

public class SIM {
	int sNum;
	SIM(int num){
		this.sNum=num;
	}
	public void setsNum(int sNum) {//设置卡号
		this.sNum = sNum;
	}
	public int getsNum() {//获取卡号
		return sNum;
	}
}

public class Phone {
	SIM sim;
	public void setSim(SIM sim) {//设置手机号
		this.sim = sim;
	}
	public SIM getSim() {
		return sim;
	}
}

public class PhoneTest {

	public static void main(String[] args) {
		SIM s1=new SIM(138540);
		SIM s2=new SIM(135734);
		Phone p=new Phone();
		p.setSim(s1);
		System.out.println("手机卡号为:"+p.getSim().getsNum());  
        p.setSim(s2);
        System.out.println("更换手机卡号为:"+p.getSim().getsNum());
	}
}

运行结果:



课堂练习5


实现代码:

public class CPU {
	 int speed;  
	    int getSpeed(){  
	        return speed;  
	    }  
	    void setSpeed(int speed){  
	        this.speed=speed;  
	    }
}
public class HardDisk {
	  int amount;  
	    int getAmount(){  
	        return amount;  
	    }  
	    void setAmount(int amount){  
	        this.amount=amount;  
	    }
}
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 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();        
    }
}


运行结果:



已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页