java练习4

来源:互联网 发布:搜狗输入法mac旧版本 编辑:程序博客网 时间:2024/06/06 12:29

课堂练习4

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

要求:

           SIM卡类负责创建SIM卡;

           Phone类负责创建手机;

          手机可以组合一个SIM卡;

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

代码:

sim卡类:

package homework;


public class SIM {
long number;
SIM(long number){
this.number=number;
}
     long getNumber(){
    return number;
     }
}

tel类:

package homework;


public class TEL {
SIM sim;
void setSIM(SIM card){
sim=card;
}
long lookNumber(){
return sim.getNumber();
}


}

测试类:

public class test {
public static void main (String arh[]){
SIM simOne=new SIM(13566666666L);
TEL tel=new TEL();
tel.setSIM(simOne);
System.out.println("手机号码:"+tel.lookNumber());
SIM simTwo=new SIM(15999999999L);
tel.setSIM(simTwo);
System.out.println("手机号码:"+tel.lookNumber());
}


}




cpu速度与容量:

代码:

cpu类:

public class CPU {
int speed;
  public void setSpeed(int m){
speed=m;
}
    int getSpeed(){
    return speed;
    }
}

pc类:

public class PC {
CPU cpu;
HardDisk HD;
public CPU getCpu() {
return cpu;
}
public void setCPU(CPU c) {
cpu=c;
}
public HardDisk getHD() {
return HD;
}
public void setHardDisk(HardDisk h) {
HD = h;
}
public void show(){
System.out.println("CPU的速度是"+cpu.speed+",CPU的容量是"+HD.amount);
}



}

hd类:

public class HardDisk {
int amount;
public void setAmout(int m){
amount=m;
}
int getAmount(){
return amount;
}
}


测试类:

public class Text {
public static void main(String arg[]){
CPU cpu=new CPU();
cpu.speed=2200;
HardDisk disk=new HardDisk();
disk.amount=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类和Apackage bzu.info.com;


import bzu.info.software.Circle;


public class A {
public static void main(String args[]){
Circle circle=new Circle(2);
Cylinder cylinder=new Cylinder(2,3);
//circle.getArea();
//cylinder.getV();
System.out.println("圆的体积是"+cylinder.getV());

}
}类置于不同的包中,通过对求体积方法设置不同的访问权限,查看并分析编译和运行结果

代码:

Circle类:

package bzu.info.software;


public class Circle {
   public int r;
   public Circle(int r) {
       this.r=r;
   }
   public double getArea(){
  return 3.14*r*r;
   }
 
}

Cylinder类:

package bzu.info.com;


import bzu.info.software.Circle;


public class Cylinder {
Circle bottom;
int h;
public Cylinder(int r,int h){
this.h=h;
this.bottom=new Circle(r);
}
public double getV(){
return bottom.getArea()*h;
}


}

A类:


package bzu.info.com;


import bzu.info.software.Circle;


public class A {
public static void main(String args[]){
Circle circle=new Circle(2);
Cylinder cylinder=new Cylinder(2,3);
//circle.getArea();
//cylinder.getV();
System.out.println("圆的体积是"+cylinder.getV());

}
}


原创粉丝点击