Static method in interface in Java 8

 278 total views,  2 views today

In this tutorial let us learn about static method in interface in Java 8.Prior to Java 8, interfaces can only have public abstract methods.

It was not possible to implement a method in the interface itself and It was also not possible to add new functionality to the existing interface without forcing all implementing classes to create an implementation of the new methods

When we need to add any new functionality to interface,then all the implementation classes must undergo changes.

Starting with Java 8, interfaces can have static and default methods that, despite being declared in an interface, have a defined behavior.

Static method in interface

Let us create an interface and add a static method

interface Vehicle {
	void start();

	void stop();

	static String speedCheck() {
	    return "Speed is controlled";
	}
}

The static speedCheck() method is available only inside of an interface. It can’t be overridden by an implementing class. To call it outside the interface the standard approach for static method call should be used

String speed = Vehicle.speedCheck();

If you would like to learn about default methods in interface, please refer to Default method in interface in Java 8.

Reference : Official documentation

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.