- /*多态的主板示例
- 电脑运行实例
- 电脑运行基于主板
- */
- interface PCI
- {
- public void open();
- public void close();
- }
- class MainBoard
- {
- public void run()
- {
- System.out.println("mainboard run");
- }
- public void usePCI(PCI p)
- {
- if(p!=null)
- {
- p.open();
- p.close();
- }
- }
- }
- class NetCard implements PCI
- {
- public void open()
- {
- System.out.println("netcard open");
- }
- public void close()
- {
- System.out.println("netcard close");
- }
- }
- class SoundCard implements PCI
- {
- public void open()
- {
- System.out.println("SoundCard open");
- }
- public void close()
- {
- System.out.println("SoundCard close");
- }
- }
- /*
- class MainBoard
- {
- public void run()
- {
- System.out.println("mainboard run");
- }
- public void useNetCard(NetCard c)
- {
- c.open();
- }
- }
- class NetCard
- {
- public void open()
- {
- System.out.println("netcard open");
- }
- public void close()
- {
- System.out.println("netcard close");
- }
- }
- */
- class Demo6
- {
- public static void main(String[] args)
- {
- //System.out.println("Hello World!");
- MainBoard m=new MainBoard();
- //m.run();
- //m.useNetCard(new NetCard());
- m.usePCI(null);
- m.usePCI(new NetCard());
- m.usePCI(new SoundCard());
- }
- }
复制代码 |
|