//amb.java --- demostrate Inheritance and Polymorphism. Also show you //..how to do Runtime type checking. @CopyLeft by tsaiwn@csie.nctu.edu.tw import java.awt.*; public class amb extends MyApplet { public static final int N_OBJ = 3; static Frame f = new Frame(" <<< Polymorphism >>> "); public static void main(String[ ] args) { Animal a[ ] = new Animal[N_OBJ]; a[0] = new Animal(1); a[1] = new Cat(2); a[2] = new Mankind(3); for(int i = 0; i< N_OBJ ; ++i) a[i].init( ); // Polymorphism for(int i = 0; i < N_OBJ; ++i) { showMessage(a[i]); f.add(a[i]); f.setSize(300,300); f.validate( ); f.setVisible(true); // Polymorphism a[i].talk( ); try { Thread.sleep(568); } catch (Exception e) { } print("Hit Return ..."); int c=0; try{ c=System.in.read();} catch (Exception e) { } if(c!=13) try{ c=System.in.read();} catch (Exception e) { } if( i < N_OBJ -1 ) f.remove(a[i]); println(""); } newPlayFile("bye.au"); try { Thread.sleep(988); } catch (Exception e) { } System.exit(0); } static void showMessage(Object o) { // 由 Object 決定秀啥 message f.setTitle(""+o); if(o instanceof Mankind) print("Mankind talking..."); else if(o instanceof Cat ) print("Cat talking..."); else if(o instanceof Animal) print("Animal talking..."); } } // class amb class Animal extends MyApplet { // Animal is-a MyApplet (is-a Applet) protected int n = 0; public Animal(int n) { this.n = n; } void talk( ) { for(int i=1; i <= n; ++i) { beep(); newPlayFile("chichi.au"); } } } class Cat extends Animal { public Cat(int n) { super(n); } public void init ( ) { PicturePanel p = new PicturePanel("images/cat.gif", true); Panel p23 = new Panel(new GridLayout(2,1)); PicturePanel p2a = new PicturePanel("images/cat1.gif", false); PicturePanel p2b = new PicturePanel("images/cat2.gif", false); p23.add(p2a); p23.add(p2b); setLayout( new GridLayout(1,2)); // Layout of this Cat add(p); add(p23); // put p and p23 into the Cat (is an Applet too) } void talk( ) { for(int i=1; i <= n; ++i) newPlayFile("meow.wav"); } } // Cat class Mankind extends Animal { public Mankind(int n) { super(n); } public void init ( ) { PicturePanel p = new PicturePanel("images/mypic.jpg", true); setLayout( new GridLayout(1,1)); add(p); } // init void talk( ) { // new talk( ) for Mankind, 若不寫, 則會用原先 Animal 的 talk for(int i=1; i <= n; ++i) { newPlayFile("yahoo.au"); try { Thread.sleep(358); } catch (Exception e) { } } } // talk void talk(String what) { newPlayFile(what); } // talk(String) } // class Mankind