Java8新機能 デフォルトメソッド
前回に引き続き、Java8の新機能で遊んでみました。
今回はデフォルトメソッドです。
これまではInterfaceを実装したらクラス側で処理を記述する必要がありましたが、Interfaceにデフォルト処理を記述することで、クラス側の記述が不要になります。
まずは確認
public interface TestInterface { default public void printTest() { System.out.println("Hello Interface!"); } }
public class TestClass implements TestInterface { public static void main(String[] args) throws Exception { TestClass testClass = new TestClass(); testClass.printTest(); } }
>java TestClass
Hello Interface!
2つのInterfaceに同一メソッドの処理が定義されている場合
public interface TestInterface1 { default public void printTest() { System.out.println("Hello Interface1!"); } }
public interface TestInterface2 { default public void printTest() { System.out.println("Hello Interface2!"); } }
public class TestClass implements TestInterface1, TestInterface2 { public static void main(String[] args) throws Exception { TestClass testClass = new TestClass(); testClass.printTest(); } }
>javac TestClass.java
TestClass.java:1: エラー: クラス TestClassは型TestInterface1とTestInterface2からprintTest()の関連しないデフォルトを継承します
public class TestClass implements TestInterface1, TestInterface2 {
^
エラー1個
コンパイルエラーになりました。エラーメッセージが分かり難いですがw
クラス側で処理を実装するとOKでした。
public class TestClass implements TestInterface1, TestInterface2 { public static void main(String[] args) throws Exception { TestClass testClass = new TestClass(); testClass.printTest(); } public void printTest() { System.out.println("Hello Class!"); } }
>javac TestClass.java
>java TestClass
Hello Class!
Interfaceで定義された処理をsuperで呼べるのか
public class TestClass implements TestInterface1, TestInterface2 { public static void main(String[] args) throws Exception { TestClass testClass = new TestClass(); testClass.printTest(); } public void printTest() { super.printTest(); } }
>javac TestClass.java
TestClass.java:7: エラー: シンボルを見つけられません
super.printTest();
^
シンボル: メソッド printTest()
エラー1個
だめでした。
Interfaceを1つだけにしてもやっぱりだめでした。
と思ったら、Interface名をsuperの前に指定したらいけるようです。
public class TestClass implements TestInterface1, TestInterface2 { public static void main(String[] args) throws Exception { TestClass testClass = new TestClass(); testClass.printTest(); } public void printTest() { TestInterface1.super.printTest(); } }
>javac TestClass.java
>java TestClass
Hello Interface1!
遊んでみて
え、多重継承となにが違うの?
だれかおせーて orz