Interfaces change in Java 9 – Introduction of private methods

Prior to Java 8 an interface could have either constant variables or method definitions. Java 8 made it possible to declare default and static methods with implementations in interfaces. However, you could not declare these methods as private. So if you have written some helper method it will get exposed to implementing classes also. Have a look at this interface :

public interface InterfaceExample {
 
	void method1();
 
	default void method2(){
                methodHelper();
		//do something
	}
 
	static void method3(){
                methodHelper();
		//do something
	}
 
	default void methodHelper(){
		//A helper method which should be visible to this interface only
	}
}
 
class Impl implements InterfaceExample{
 
	@Override
	public void method1() {
		// TODO Auto-generated method stub
 
	}
 
	public static void main(String[] args) {
		Impl impl = new Impl();
		impl.methodHelper();
 
	}
 
}

methodHelper‘ was a helper method which should have been visible to the methods of interface only. But it can be accessed from the objects of implementing classes also.

Java 9 has rectified this mistake and now you can declare private methods which will be visible only to the Interface

public interface InterfaceExample {
 
	void method1();
 
	default void method2(){
		//do something
	}
 
	static void method3(){
		//do something
	}
 
	<strong>private</strong> void methodHelper(){
 
	}
}

This way we can restrict the visibility of method methodHelper

Mar Java Mit Java 🙂

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

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