[20-05-06][Thinking in Java 12]Java Interfaces 2 - Interface

Posted mirai3usi9

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[20-05-06][Thinking in Java 12]Java Interfaces 2 - Interface相关的知识,希望对你有一定的参考价值。

1 package test_3_1;
2 
3 public enum Note {
4     
5     MIDDLE_C, C_SHARP, B_FLAT;
6 }

 

 1 package test_3_1;
 2 
 3 interface Instrument {
 4 
 5     // 自动static final
 6     int VALUE = 5;
 7     
 8     // 没有方法体,自动public
 9     void play(Note n);
10     void adjust();
11 }

 

 1 package test_3_1;
 2 
 3 public class Wind implements Instrument {
 4 
 5     public void play(Note n) {
 6         
 7         System.out.println(this + ".play() " + n);
 8     }
 9     
10     public String toString() {
11         
12         return "Wind";
13     }
14     
15     public void adjust() {
16         
17         System.out.println(this + ".adjust() ");
18     }
19 }

 

 1 package test_3_1;
 2 
 3 public class Music {
 4 
 5     public static void tune(Instrument i) {
 6 
 7         i.play(Note.MIDDLE_C);
 8     }
 9 
10     public static void tuneAll(Instrument[] e) {
11 
12         for (Instrument i : e)
13             tune(i);
14     }
15 
16     public static void main(String[] args) {
17 
18         Instrument[] orchestra = { new Wind(), new Percussion(), new Stringed(), new Brass(), new Woodwind() };
19 
20         tuneAll(orchestra);
21 
22     }
23 
24 }

 

 1 package test_3_1;
 2 
 3 public class Stringed implements Instrument {
 4 
 5     public void play(Note n) {
 6 
 7         System.out.println(this + ".play() " + n);
 8     }
 9 
10     public String toString() {
11 
12         return "Stringed";
13     }
14 
15     public void adjust() {
16 
17         System.out.println(this + ".adjust() ");
18     }
19 }

 

1 package test_3_1;
2 
3 public class Brass extends Wind {
4 
5     public String toString() {
6         
7         return "Brass";
8     }
9 }

 

1 package test_3_1;
2 
3 public class Woodwind extends Wind {
4 
5     public String toString() {
6         
7         return "Woodwind";
8     }
9 }

 

 1 package test_3_1;
 2 
 3 public class Music {
 4 
 5     public static void tune(Instrument i) {
 6 
 7         i.play(Note.MIDDLE_C);
 8     }
 9 
10     public static void tuneAll(Instrument[] e) {
11 
12         for (Instrument i : e)
13             tune(i);
14     }
15 
16     public static void main(String[] args) {
17 
18         Instrument[] orchestra = { new Wind(), new Percussion(), new Stringed(), new Brass(), new Woodwind() };
19 
20         tuneAll(orchestra);
21 
22     }
23 
24 }

 

结果如下:

Wind.play() MIDDLE_C
Percussion.play() MIDDLE_C
Stringed.play() MIDDLE_C
Brass.play() MIDDLE_C
Woodwind.play() MIDDLE_C

以上是关于[20-05-06][Thinking in Java 12]Java Interfaces 2 - Interface的主要内容,如果未能解决你的问题,请参考以下文章

Thinking In Java

Hacker Rank: Two Strings - thinking in C# 15+ ways

Thinking in Java & Writing in Python

Thinking in LINQ, Chapter 1, Thinking Functionally

Thinking in Java

Thinking in React(翻译)