Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static methods in java interface

As far as I know you cannot declare static methods in interface body. However, accidentally I found peculiar piece of code on http://docs.oracle.com/ site. Here is the link

Namelly

public interface TimeClient 
{
void setTime(int hour, int minute, int second);
void setDate(int day, int month, int year);
void setDateAndTime(int day, int month, int year,
                           int hour, int minute, int second);
LocalDateTime getLocalDateTime();

static 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 ZonedDateTime getZonedDateTime(String zoneString) {
    return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
    }
}

this interface has a static method getZoneId

I am lost... could anyone explain please

like image 820
Russell'sTeapot Avatar asked Apr 18 '14 06:04

Russell'sTeapot


2 Answers

You are the witness of two new features in Java 8 here:

  • static methods in interfaces,
  • virtual extension methods.

In the code sample you provide, getZoneId() illustrates the first novelty, and .getZoneDateTime() the second one.

The second one in particular is what has allowed the Collection interface to be extended with supplementary methods such as .stream(), for example, without breaking backwards compatibility. See here for an illustration.

The first one allows to avoid writing "method bags" classes which often exist only to provide utility static methods over interfaces. One such example would be Guava's Functions class (not to be mixed with Java 8's Function which it basically stole from Guava, along with Predicate and a few others)

like image 65
fge Avatar answered Sep 23 '22 20:09

fge


Java 8 now has the idea of "default" method implementations in interfaces:

http://blog.hartveld.com/2013/03/jdk-8-13-interface-default-method.html

like image 35
Sean Owen Avatar answered Sep 22 '22 20:09

Sean Owen