本帖最后由 清秋 于 2011-11-21 09:49 编辑
day08视频中的多态主板的例子。- /*
- 需求:
- 电脑运行实例
- 电脑运行依赖于主板
- */
- interface PCI
- {
- public void open();
- public void close();
- }
- class MainBoard
- {
- public void run()
- {
- System.out.println("maiboard 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 DuoTai5
- {
- public static void main(String[] args)
- {
- MainBoard mb = new MainBoard();
- mb.run();
- mb.usePCI(null);
- mb.usePCI(new NetCard());
- mb.usePCI(new SoundCard());
- }
- }
复制代码 例子中用接口实现。
对接口和抽象有些模糊
不知道这两种方式有何区别。
抽象
- abstract class PCI
- {
- public abstract void open();
- public abstract void close();
- }
- class MainBoard
- {
- public void run()
- {
- System.out.println("maiboard run");
- }
- public void usePCI(PCI p)
- {
- if ( p != null )
- {
- p.open();
- p.close();
- }
- }
- }
- class NetCard extends PCI
- {
- public void open()
- {
- System.out.println("netcard open");
- }
- public void close()
- {
- System.out.println("netcard close");
- }
- }
- class SoundCard extends PCI
- {
- public void open()
- {
- System.out.println("soundcard open");
- }
- public void close()
- {
- System.out.println("soundcard close");
- }
- }
- class DuoTai5
- {
- public static void main(String[] args)
- {
- MainBoard mb = new MainBoard();
- mb.run();
- mb.usePCI(null);
- mb.usePCI(new NetCard());
- mb.usePCI(new SoundCard());
- }
- }
复制代码 |