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

后端 未结 24 1097
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:35

    You can't define static methods in an interface because static methods belongs to a class not to an instance of class, and interfaces are not Classes. Read more here.

    However, If you want you can do this:

    public class A {
      public static void methodX() {
      }
    }
    
    public class B extends A {
      public static void methodX() {
      }
    }
    

    In this case what you have is two classes with 2 distinct static methods called methodX().

提交回复
热议问题