JAVA实验四 类和对象

1、编写一个类,该类创建的对象可以输出英文字母表。

class alphabet {
	void print() {
		char a='a';
		char A='A';
		for (int i = 0; i < 26; i++) 
			System.out.print(a++ + " ");
		System.out.println();
		for (int i = 0; i < 26; i++) 
			System.out.print(A++ + " ");
	}
}
public class exc1 {
	public static void main(String[] args) {
		alphabet alp = new alphabet();
		alp.print();
	}
}

2、用类描述计算机中CPU的速度和硬盘的容量。要求Java应用程序有4个类,名字分别是PC,CPU和HardDisk和Test,其中Test是主类。
 PC类与CPU和HardDisk类关联的UML图(图1)
其中,CPU类要求getSpeed()返回speed的值;要求setSpeed(int m)方法将参数m的值赋值给speed。HardDisk类要求getAmount()返回amount的值,要求setAmount(int m)方法将参数m的值赋值给amount。PC类要求setCUP(CPU c) 将参数c的值赋值给cpu,要求setHardDisk (HardDisk h)方法将参数h的值赋值给HD,要求show()方法能显示cpu的速度和硬盘的容量。
 主类Test的要求
① main方法中创建一个CPU对象cpu,cpu将自己的speed设置为2200,
② main方法中创建一个HardDisk对象disk,disk将自己的amount设置为200,
③ main方法中创建一个PC对象pc,
④ pc调用setCUP(CPU c)方法,调用时实参是cpu,
⑤ pc调用setHardDisk (HardDisk h)方法,调用时实参是disk,
⑥ pc调用show()方法。


class CPU {
	int speed;
	int getSpeed() {
		return speed;
	}
	void setSpeed(int m) {
		speed = m;
	}
}
class HardDisk {
	int amount;
	int getAmount() {
		return amount;
	}
	void setAmount(int m) {
		amount = m;
	}
}
class PC {
	CPU cpu;
	HardDisk HD;
	void setCPU(CPU c) {
		cpu = c;
	}
	void setHardDisk(HardDisk h) {
		HD = h;
	}
	void show() {
		System.out.println("cpu speed:" + cpu.getSpeed());
		System.out.println("HD amount:" + 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();
	}
}

仅作留档。

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值