Last Modified 2022.1.27
Default Method
Default methods allow you to define an interface that contains methods with an implementation. The introduction of default methods was an inevitable choice to change the API while maintaining compatibility with legacy code. This new feature makes Java a language that allows multiple inheritances. Default methods have the default keyword before the return type.
Assuming C inherits from A and B, A and B have the same method.
- If A is an interface and B is a class, then C inherits B's method.
- If A and B are both interfaces and Java cannot determine the priority of default methods, a compile error occurs. In this case, you must explicitly override the default method you want to call and call it.
If A is an interface and B is a class, then C inherits B's method.
package net.java_school.examples; public interface A1Interface { public default String hello() { return "A1 Interface says hello"; } }
package net.java_school.examples; public class B1Class { public String hello() { return "B1 Class says hello"; } }
package net.java_school.examples; public class C1Class extends B1Class implements A1Interface { public static void main(String[] args) { C1Class c1 = new C1Class(); System.out.println(c1.hello()); } }
B1 Class says hello
Sometimes, you must explicitly override the default method you want to call and call it.
package net.java_school.examples; public interface A2Interface { public default String hello() { return "A2 Interface says hello"; } }
package net.java_school.examples; public interface B2Interface { public default String hello() { return "B2 Interface says hello"; } }
package net.java_school.examples; public class C3Class implements A2Interface,B2Interface { }
The C2Class class occurs a compile error saying Duplicate default methods named hello. To avoid compile errors, you must explicitly override the method you choose.
package net.java_school.examples; public class C2Class implements A2Interface,B2Interface { @Override public String hello() { return B2Interface.super.hello();//B2Interface's hello(). } public static void main(String[] args) { C2Class c2 = new C2Class(); System.out.println(c2.hello()); } }
B2 Interface says hello
Final source: https://github.com/kimjonghoon/multipleInheritance
How to run
~/multipleInheritance$ cd src/net/java_school/examples/ ~/multipleInheritance/src/net/java_school/examples$ javac -d ../../../../bin *.java ~/multipleInheritance/src/net/java_school/examples$ cd - ~/multipleInheritance$ java -cp ./bin net.java_school.examples.Test B1 Class says hello B2 Interface says hello