Static Interface Methods in Java 8

Introduction
From Java 8 onwards, static methods are allowed in interfaces. As you already know static methods are class level methods and hence are not inherited.
Use
Only utility methods are to be defined as static methods in interfaces.
As static methods are not specific to any instance, they are accessed using the interface name.

Example

package learn.staticmethods;

interface Player {
	public static String getPlayerFullName(String firstName, String middleName, String lastName) {
		String fullName = String.join(" ", firstName, middleName, lastName);
		return fullName;
	}
}

public class StaticInter1 {
	public static void main(String args[]) {
		String fullName = Player.getPlayerFullName("Seema", "Sobhana", "Richard");
		System.out.println("Full Name is " + fullName);
	}
}

Here, the getPlayerFullName() is a static method which is a utility function that joins all the names to get the full name of a player. This program prints “Seema Sobhana Richard”.

Revision Points

  • Static methods are not inherited, and hence cannot be overridden.
  • Static methods are invoked using the interface name.

Quiz

1. What is the result of compiling and running the below program?

package learn.staticmethods;

interface PrintableC {
	public static void printWithSeparation(String... s) {
		System.out.println(String.join(",", s[0], s[1]));
	}
}

interface PrintableH extends PrintableC {
	public static void printWithSeparation(String... s) {
		System.out.println(String.join("-", s[0], s[1]));
	}
}

public class StaticInter1 {
	public static void main(String args[]) {
		PrintableC.printWithSeparation("Hello", "World");
		PrintableH.printWithSeparation("Hello", "World");
	}
}

a. Does not compile
b. Compiles, but fails at run time
c. Compiles and runs correctly printing "Hello,World" followed by "Hello-World"
d. Compiles and runs correctly printing "Hello,World" twice

For answers with explanations, please refer to http://talks.skilltoz.com/quiz-on-java-8-static-interface-methods/

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *