Java 9 Private Interface Method

In this article, we’re gonna take a look at Java 9 Private Interface Method which helps us avoid duplicate code and keep encapsulation for interface.

1. Java 8 – Interface

Java 8 provides 2 new features for Interface: default methods and static methods.

This is an example of Java 8 interface:


public interface ICustomerService {

	default void healthcare(String name) {
		System.out.println(name + " registers for customer service.");
		System.out.println("-- get HealthCare Service.");
	}

	default void consult(String name) {
		System.out.println(name + " registers for customer service.");
		System.out.println("-- get Consultation Service.");
	}
}

To make code easy to read and clear, we can create new register() method inside:


public interface ICustomerService {

	default void healthcare(String name) {
		register(name);
		System.out.println("-- get HealthCare Service.");
	}

	default void consult(String name) {
		register(name);
		System.out.println("-- get Consultation Service.");
	}

	default void register(String name) {
		System.out.println(name + " registers for customer service.");
	}
}

So, what is problem?
-> We don’t want to public register() method, it is just an inner private method which handles a specific function.
-> We don’t want another interface or class which implements this interface can access or inherit register() method.

2. Java 9 – new Interface

Java 9 makes those things convenient by providing a new feature for interface: private method/private static method.

For the example above, just change default modifier to private modifier:


public interface ICustomerService {

	default void healthcare(String name) {
		register(name);
		System.out.println("-- get HealthCare Service.");
	}

	default void consult(String name) {
		register(name);
		System.out.println("-- get Consultation Service.");
	}

	private void register(String name) {
		System.out.println(name + " registers for customer service.");
	}
}

That’s private interface method, simple but useful.



By grokonez | March 25, 2017.

Last updated on April 28, 2021.



Related Posts


1 thought on “Java 9 Private Interface Method”

Got Something To Say:

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

*