Why can't static methods be abstract in Java?

后端 未结 25 2884
不思量自难忘°
不思量自难忘° 2020-11-22 08:34

The question is in Java why can\'t I define an abstract static method? for example

abstract class foo {
    abstract void bar( ); // <-- this is ok
    ab         


        
25条回答
  •  猫巷女王i
    2020-11-22 08:57

    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, along with default methods static methods are also allowed in an interface. 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.

    A nice example of this is:

    list.sort(ordering);
    

    instead of

    Collections.sort(list, ordering);
    

    Another example of using static methods is also given in 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));
        }    
    }
    

提交回复
热议问题