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

后端 未结 24 1139
没有蜡笔的小新
没有蜡笔的小新 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:33

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

    Actually you can in Java 8.

    As per Java doc:

    A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods

    In Java 8 an interface can have default methods and static methods. This makes it easier for us to organize helper methods in our libraries. We can keep static methods specific to an interface in the same interface rather than in a separate class.

    Example of default method:

    list.sort(ordering);
    

    instead of

    Collections.sort(list, ordering);
    

    Example of static method (from doc itself):

    public interface TimeClient {
        // ...
        static public ZoneId getZoneId (String zoneString) {
            try {
                return ZoneId.of(zoneString);
            } catch (DateTimeException e) {
                System.err.println("Invalid time zone: " + zoneString +
                    "; using default time zone instead.");
                return ZoneId.systemDefault();
            }
        }
    
        default public ZonedDateTime getZonedDateTime(String zoneString) {
            return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
        }    
    }
    

提交回复
热议问题