使用java写一个简单的面向对象类的例子
编写一个电脑类,u盘类,光驱类,显示器类,电源类,电源一旦关闭,则内存无法访问
CDROM类
//光驱类 public class CDROM { public void cdromopen() { System.out.println("光驱打开"); } public void cdromclose() { System.out.print("光驱关闭"); } }
Power类
package test25; //电源 public class Power { private boolean on; private int div;//电流 public boolean on() { return on; } public void on(boolean on) { this.on=on; } public int getdiv() { return div; } public void setdiv(int div) { this.div=div; } }
computer类
//电脑 public class computer { private Power power; private CDROM cdrom; public Power getPower() { return power; } public void setPower(Power power) { this.power = power; } public CDROM getCdrom() { return cdrom; } public void setCdrom(CDROM cdrom) { this.cdrom = cdrom; } public void poweron() { getPower().on(true); } public void poweroff() { getPower().on(false); } public void oopencdrom() { if(getPower().on()) { getCdrom().cdromopen(); } else { System.out.println("没开电源"); } } public void closeecdrom() { if(getPower().on()) { getCdrom().cdromclose(); } else { System.out.println("没开电源"); } } public static void main(String[] args) { computer c1=new computer(); CDROM cr1=new CDROM(); Power power=new Power(); power.setdiv(5); power.on(true); c1.setCdrom(cr1); c1.setPower(power); c1.poweron(); c1.oopencdrom(); c1.closeecdrom(); c1.poweroff(); c1.oopencdrom(); } }
最终打印结果为
光驱打开
光驱关闭
没开电源
通过上述列子了解了面向对象的基本内容,未来还很长 继续努力吧