// Basic example concerning interface // An interface is like a .h header in C++: It gives a specification but // does not implement it. interface athlete { void score(); } class basketballplayer implements athlete { public void dribble() { System.out.println("boing boing boing"); } public void score() { System.out.println("slam dunk"); } } class footballplayer implements athlete { public void tackle() { System.out.println("eat dirt!"); } public void score() { System.out.println("touchdown"); } } class baseballplayer implements athlete { public void pitch() { System.out.println("zing"); } public void score() { System.out.println("home run"); } } public class interfaces { public static void main(String[] args) { athlete A; A = new footballplayer(); // A.tackle(); -- gives compiler error (A's static type is athlete). // ((footballplayer)A).tackle(); -- this will work A.score(); // prints touchdown // The following line, may change A's run-time (dynamic type). // Obviously it cannot be predicated at compile-time. At compile // time, the type of A is just "athlete" -the type it was declared as. if (Math.random()<0.5) A = new basketballplayer(); A.score(); // prints touchdown or slam dunk (DYNAMIC Dispatch) // a polymorphic array of athletes: athlete[] T = new athlete[3]; T[0] = new basketballplayer(); T[1] = new baseballplayer(); T[2] = new footballplayer(); for (int i=0;i