What does Interface in Java 8 Look Like?

0

Before we go into looking at different aspects of interface in Java 8, lets look at some of the definitions found on some of the source-of-truth websites that seem to contradict the definition of Interface in Java by defining it with a generic definition despite the fact that interface got evolved (such as below 🙂 and has got a new definition in Java 8. Whether or not, the evolved interface in Java 8 is a good move, is beyond the scope of this article. However, please feel free to share your comments.

interface evolution

Lets look at some of the following definitions of a Java interface I took from the web at the time of writing this blog. 

Definition 1:  Java interface (on Wikipedia)

An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final). An interface never contains method implementations (i.e. function “bodies”).

Definition 2: What is an Interface? (Oracle page)

In its most common form, an interface is a group of related methods with empty bodies. A bicycle’s behavior, if specified as an interface, might appear as follows:

interface Bicycle {
    void changeCadence(int newValue);
    void changeGear(int newValue);
    void speedUp(int increment);
    void applyBrakes(int decrement);
}

And, now, see the following definition that has been taken from docs.oracle.com which describes Java interface in a contradictory manner.

Definition 3: Interfaces in Java 8 (Oracle Page)

In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Following is sample code from this page that represents Java 8 interface. Pay attention to abstract methods, static method and default method.

public interface TimeClient {

    // Abstract methods 
    void setTime(int hour, int minute, int second);
    void setDate(int day, int month, int year);

    // Static methods
    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 Methods
    default public ZonedDateTime getZonedDateTime(String zoneString) {
        return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
    }    
}

Which of the above definitions are TRUE? 

Well, all of the above definitions are TRUE but with respect to different Java versions. Someone needs to update WIKIPEDIA page titled Interface(Java) and Oracle page with the mention of Java 8 version and changed interface definition.

What is Interface in Java?

Asking that question may be incorrect. One may need to specify the Java version. So, lets rewrite the question.

What is Interface in Java 8?

Interface in Java 8 is a reference type that contains abstract methods, default methods, and static methods apart from constants and nested types. Read this page to know various details on Java Interface.

As a matter of fact, I tried with following code with Java 8 and it worked without any complaints.

public interface HelloInterface {
	// Abstract method
	void sayHello( String name );
	// Static method
	static void sayThanks() {
		System.out.println( "Thank You!" );
	}
	// Default method
	default void sayHelloWorld() {
		System.out.println( "Hello World!" );
	}
}

public class HelloInterfaceImpl implements HelloInterface {

	@Override
	public void sayHello(String name) {
		System.out.println( "Hello " + name );
	}

	public static void main(String[] args) {

		HelloInterfaceImpl hi = new HelloInterfaceImpl();

		hi.sayHello( "VitalFlux.com" ); // Abstract method implementation called
		hi.sayHelloWorld(); //Default method called
		HelloInterface.sayThanks(); //Static method called				
	}

}

Just to make sure, I tried HelloInterface with Java 7 and following screenshots represents the error.

interface error

 

Why Interface in Java had to evolve to contain static and default methods?

Following describes, in brief, the reasons why they decided to include static and default methods in a Java interface:

 

Default Methods

Default methods are identified by the specifier, default, as shown in above example. Following are key reasons why default methods had to be added in an interface:

  • Need to add new functionality to the existing interfaces and ensure binary compatibility with code written for older versions of those interfaces.
  • Need to add methods that accept lambda expressions as parameters to existing interfaces.

Static Methods

Static methods have been added to enable developers define static methods specific to an interface within an interface rather than in a separate util class or so.

 

And, then, Java 8 Interface Got a New Buddy: Functional Interface

As per the Oracle java docs on this page, following is the definition of functional interface:

Functional interfaces provide target types for lambda expressions and method references. Each functional interface has a single abstract method, called the functional method for that functional interface, to which the lambda expression’s parameter and return types are matched or adapted.

Conceptually, a functional interface has JUST ONE abstract method. But it can have multiple static and default methods. Functional interfaces can be annotated with @FunctionalInterface. However, that is not necessary. The compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a @FunctionalInterface annotation is present on the interface declaration.

[adsenseyu1]

Ajitesh Kumar
Share.

Leave A Reply

Time limit is exhausted. Please reload the CAPTCHA.