面向对象案例 - 多类合作 - 电脑组装0430
/*
* 键盘
键盘也可以看做是一个磊
成员变量:
品牌
按键个数
*/
public class Keyboard {
private String name;
private int keyCount;
public Keyboard() {}
public Keyboard(String name, int keyCount) {
this.name = name;
this.keyCount = keyCount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKeyCount() {
return keyCount;
}
public void setKeyCount(int keyCount) {
this.keyCount = keyCount;
}
}
/*
屏幕
屏幕可以看做是一个类
成员变量:
品牌
尺寸
*/
public class Screen {
private String name;
private float size;
public Screen() {}
public Screen(String name, float size) {
this.name = name;
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSize() {
return size;
}
public void setSize(float size) {
this.size = size;
}
}
/*
* PC电脑类
成员变量:
屏幕类对象
键盘类对象
成员方法:
换屏幕
换键盘
电脑展示配置
*
* */
//
public class PC {
private Screen screen;
private Keyboard keyboard;
public PC() {}
public PC(Screen screen, Keyboard keyboard) {
this.screen = screen;
this.keyboard = keyboard;
}
public void show() {
System.out.println("屏幕品牌是" + this.screen.getName() + ",屏幕大小是" + this.screen.getSize());
System.out.println("键盘品牌是" + this.keyboard.getName() + ",键盘键数是" + this.keyboard.getKeyCount() );
}
public Screen getScreen() {
return screen;
}
public void setScreen(Screen screen) {
this.screen = screen;
}
public Keyboard getKeyboard() {
return keyboard;
}
public void setKeyboard(Keyboard keyboard) {
this.keyboard = keyboard;
}
}
测试类使用了匿名对象
package com.qfedu.a.computer2;
public class Demo {
public static void main(String[] args) {
PC pc = new PC(new Screen("京东方",26.8F), new Keyboard("杂牌",84));
pc.show();
System.out.println("--------------");
// 换键盘
pc.setKeyboard(new Keyboard("机械键盘",84));
System.out.println(pc.getKeyboard().getName());// 通过“。”的方式可以得到匿名对象的值
pc.show();
System.out.println("--------------");
//换显示器
pc.setScreen(new Screen("杂牌", 28.8F));
pc.show();
System.out.println("--------------");
}
}