|
| 1 | +// |
| 2 | +// |
| 3 | +public class Driver { |
| 4 | + |
| 5 | + public static void main(String[] args) { |
| 6 | + String[] friends = {"jim","kate","bill","mark","devin","alice","melvin","jeremy","bob"}; |
| 7 | + String space = " "; |
| 8 | + |
| 9 | + // example 1 - normal show method |
| 10 | + Messenger messager1 = new MyMessenger(friends); |
| 11 | + messager1.show(); |
| 12 | + |
| 13 | + // example 2 - create a class to override the show method |
| 14 | + Messenger messager2 = new BetterMessenger(friends); |
| 15 | + messager2.show(); |
| 16 | + |
| 17 | + // example 3 - create an anonymous class to override the show method |
| 18 | + Messenger messager3 = new MyMessenger(friends) { |
| 19 | + public void show() { |
| 20 | + for (String name : contactList) { |
| 21 | + System.out.print(name + " "); |
| 22 | + } |
| 23 | + System.out.println(); |
| 24 | + } |
| 25 | + }; |
| 26 | + messager3.show(); |
| 27 | + |
| 28 | + // example 4 - create an anonymous class to implement the entire interface |
| 29 | + final String sp = space; |
| 30 | + final String[] names = friends; |
| 31 | + Messenger messager = new Messenger() { |
| 32 | + |
| 33 | + public void send(String message) { |
| 34 | + for (String name : names) { |
| 35 | + System.out.println(name + ": " + message); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + public void show() { |
| 40 | + for (String name : names) { |
| 41 | + System.out.print(name + sp); |
| 42 | + } |
| 43 | + System.out.println(); |
| 44 | + } |
| 45 | + }; |
| 46 | + messager.show(); |
| 47 | + |
| 48 | + // changing space variable now works because we created the sp variable. |
| 49 | + space = " "; |
| 50 | + } |
| 51 | + |
| 52 | +} |
| 53 | +// |
| 54 | +// |
| 55 | +class MyMessenger implements Messenger { |
| 56 | + |
| 57 | + protected String[] contactList; |
| 58 | + |
| 59 | + public MyMessenger(String[] names) { |
| 60 | + contactList = names; |
| 61 | + } |
| 62 | + |
| 63 | + public void send(String message) { |
| 64 | + for (String name : contactList) { |
| 65 | + System.out.println(name + ": " + message); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + public void show() { |
| 70 | + for (String name : contactList) { |
| 71 | + System.out.println(name); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | +} |
| 76 | +// |
| 77 | +// |
| 78 | +class BetterMessenger extends MyMessenger { |
| 79 | + |
| 80 | + public BetterMessenger (String[] names) { |
| 81 | + super(names); |
| 82 | + } |
| 83 | + |
| 84 | + @Override |
| 85 | + public void show() { |
| 86 | + for (String name : contactList) { |
| 87 | + System.out.print(name + " "); |
| 88 | + } |
| 89 | + System.out.println(); |
| 90 | + } |
| 91 | +} |
| 92 | +// |
| 93 | +// |
| 94 | +interface Messenger { |
| 95 | + |
| 96 | + void send(String message); |
| 97 | + void show(); |
| 98 | + |
| 99 | +} |
0 commit comments