Why can't I define a static method in a Java interface?

后端 未结 24 1708
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 05:44

EDIT: As of Java 8, static methods are now allowed in interfaces.

Here\'s the example:

public interface IXMLizable         


        
24条回答
  •  情书的邮戳
    2020-11-22 06:47

    With the advent of Java 8 it is possible now to write default and static methods in interface. docs.oracle/staticMethod

    For example:

    public interface Arithmetic {
    
        public int add(int a, int b);
    
        public static int multiply(int a, int b) {
            return a * b;
        }
    }
    
    public class ArithmaticImplementation implements Arithmetic {
    
        @Override
        public int add(int a, int b) {
            return a + b;
        }
    
        public static void main(String[] args) {
            int result = Arithmetic.multiply(2, 3);
            System.out.println(result);
        }
    }
    

    Result : 6

    TIP : Calling an static interface method doesn't require to be implemented by any class. Surely, this happens because the same rules for static methods in superclasses applies for static methods on interfaces.

提交回复
热议问题