import java.lang.reflect.Method; /** * JavaSE 8新特性:<span style="background-color: rgb(255, 255, 0);">1.接口能夠定義非抽象方法</span> 但必須使用default或者staic關鍵字來修飾 */ public class DefaultMethod { public interface Chinese { //小結:<span style="background-color: rgb(255, 255, 0);">2.JDK1.8規定只能在接口定義defult方法 且必須加Body實現</span> default String speak() { return "會說普通話!"; } //小結:<span style="background-color: rgb(255, 255, 0);">3.接口的默認實現方法支持重載</span> default String speak(String language) { return "會說"+language; } //小結:<span style="background-color: rgb(255, 255, 0);">4.接口能夠定義static方法</span> static void hehe() { System.out.println("我不告訴你"); } } //小結:<span style="background-color: rgb(255, 255, 0);">4.接口的default方法能夠被子接口重寫成default方法</span> public interface GuangDong extends Chinese{ @Override public default String speak() { return "粵語"; } } //小結:<span style="background-color: rgb(255, 255, 0);">5.接口的默認方法還能夠被子接口重寫成抽象方法!!</span> public interface Mayun extends Chinese{ @Override public String speak(); } public static void main(String[] args) throws Exception{ //小結:6.若是實現類沒有重寫接口的默認方法,則該類直接調用接口的默認實現方法 System.out.println(new Chinese(){}.speak()); System.out.println(new Chinese(){}.speak("粵語")); //小結:7.接口的default方法能夠被子類重寫成普通方法 System.out.println(new Chinese(){public String speak() {return "會說鳥語";}}.speak()); //小結:<span style="background-color: rgb(255, 255, 0);">JDK1.8甚至容許直接調用接口的靜態方法</span> Chinese.hehe(); //小結:<span style="background-color: rgb(255, 255, 0);">JDK1.8 能夠經過反射來 判斷接口的某個方法是否爲default方法</span> Method m =Chinese.class.getMethod("speak"); System.out.println("It is "+m.isDefault()+" that "+m.getName()+" is default method"); } }