Home >Java >javaTutorial >How to implement Java interface composition update
Composition of interface
Constant: public static final
Abstract method: public abstract
public default return value type method name (parameter list ){}
public default void show(){}
default void show(){}
public static return value type method name (parameter list){}
public static void show(){ }
The interface name is called , which cannot be called by the implementation class name or object name.
static void show(){}
package test; public interface Inter { void show(); default void method() { System.out.println("默认方法"); } // public static void test(){ // System.out.println("静态方法"); // } static void test(){ System.out.println("静态方法"); } }
package test; public class InterImpl implements Inter{ @Override public void show() { System.out.println("show方法"); } }
package test; public class Demo { public static void main(String[] args) { Inter i = new InterImpl(); i.show(); //show方法 i.method(); // // i.test(); //报错 Inter.test(); //静态方法,接口名调用静态方法 } }1.4 Private methods in interfaces (JDK9)A new private method with a method body is added in Java 9. This is actually The foreshadowing was laid in Java 8: Java 8 allows default methods and static methods with method bodies to be defined in interfaces. This may cause a problem: when two default methods or static methods contain the same code implementation, the program must consider extracting this implementation code into a common method, and this common method does not need to be used by others. , so it is hidden by private. This is the necessity of adding private methods in Java 9.
Definition format of private methods in interface:
Format 1 (non-static) : private return value type method name (parameter list) {}
private void show() {}
Format 2 (static) :private static Return value type method name (parameter list){}
private static void method() {}
Notes on private methods in interfaces :
package test; public interface Inter { default void show1() { System.out.println("show1开始执行"); // System.out.println("初级工程师"); // System.out.println("中级工程师"); // System.out.println("高级工程师"); // show(); method(); System.out.println("show1结束"); } static void method1() { System.out.println("method1开始执行"); // System.out.println("初级工程师"); // System.out.println("中级工程师"); // System.out.println("高级工程师"); method(); System.out.println("method1结束"); } private void show(){ System.out.println("初级工程师"); System.out.println("中级工程师"); System.out.println("高级工程师"); } private static void method(){ System.out.println("初级工程师"); System.out.println("中级工程师"); System.out.println("高级工程师"); } }
The above is the detailed content of How to implement Java interface composition update. For more information, please follow other related articles on the PHP Chinese website!