Can we have static methods in interface java

Tech Tutorials

Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.

Saturday, May 16, 2020

Interface Static Methods in Java

Java 8 has added support for interface default methods as well as interface static methods which is one of the important change in Java 8 along with the addition of lambda expressions and stream API. In this post we’ll see how to use interface static methods in Java and what are the rules for using them

Static method in Java interface

Like static methods in a class, now we can write static method in interfaces too. Static methods in an interface can be called independently of any object just like how static methods are called in a class.

General form of calling the interface static method

Static methods in an interface are called by using the interface name preceding the method name.

InterfaceName.staticMethodName;

Java interface static method example

public interface MyInterface < int method1(); // default method, providing default implementation default String displayGreeting()< return "Hello from MyInterface"; >//static method static int getDefaultAmount() < return 0; >>

In the example code interface MyInterface has one static method getDefaultAmount(). Note that MyClass is not even implementing the interface MyInterface still static method of the MyInterface can be called from MyClass using the call MyInterface.getDefaultAmount();. This is because, no implementation or reference of the interface is required to call the static method.

Interface static methods are not inherited

Here interface B is extending mentioned interface MyInterface, but it can not access the static method of interface MyInterface.

interface B extends MyInterface < default String displayGreeting()< B.getDefaultAmount(); // Compiler Error return "Hello from MyInterface"; >>

Same way even if MyClass implements MyInterface still it can not access static method of MyInterface, either by using the class name or by using the object reference.

public class MyClass implements MyInterface < // provides implementation for the non-default method // of the interface @Override public int method1() < return 10; >//Overriding the default method of MyInterface public String displayGreeting() < return MyInterface.super.displayGreeting(); >public static void main(String[] args) < MyInterface myInt = new MyClass(); int num = MyInterface.getDefaultAmount(); System.out.println("num " + num); MyClass.getDefaultAmount(); // Compiler error myInt.getDefaultAmount();// Compiler error >>

Hiding interface static method

Though implementing class can’t provide implementation for the static methods of an interface but the implementing class can hide the interface static method in Java by providing method with same signature in the implementing class.

public interface MyInterface < int method1(); // default method, providing default implementation default String displayGreeting()< return "Hello from MyInterface"; >static int getDefaultAmount() < return 0; >>
public class MyClass implements MyInterface < // provides implementation for the non-default method // of the interface @Override public int method1() < return 10; >//Overriding the default method of MyInterface public String displayGreeting() < return MyInterface.super.displayGreeting(); >// static method public static int getDefaultAmount() < return 5; >public static void main(String[] args) < MyInterface myInt = new MyClass(); int num = MyInterface.getDefaultAmount(); System.out.println("num - Interface " + num); System.out.println("num - Class " + MyClass.getDefaultAmount()); >>
num - Interface 0 num - Class 5

Here getDefaultAmount() method is provided in the MyClass class also which hides the interface static method.

Читайте также:  Html сделать свою кнопку

Advantages of Java interface static methods

  • Interface static methods can be used for providing utility methods.
  • With Interface static methods we can secure an implementation by having it in static method as implementing classes can’t override them. Though we can have a method with same signature in implementing class but that will hide the method won’t override it.

That’s all for this topic Interface Static Methods in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Источник

Java 8 Interface Changes – default method and static method

Prior to java 8, interface in java can only have abstract methods. All the methods of interfaces are public & abstract by default. Java 8 allows the interfaces to have default and static methods. The reason we have default methods in interfaces is to allow the developers to add new methods to the interfaces without affecting the classes that implements these interfaces.

Why default method?

For example, if several classes such as A , B , C and D implements an interface XYZInterface then if we add a new method to the XYZInterface , we have to change the code in all the classes(A, B, C and D) that implements this interface. In this example we have only four classes that implements the interface which we want to change but imagine if there are hundreds of classes implementing an interface then it would be almost impossible to change the code in all those classes. This is why in java 8, we have a new concept “default methods”. These methods can be added to any existing interface and we do not need to implement these methods in the implementation classes mandatorily, thus we can add these default methods to existing interfaces without breaking the code.

We can say that concept of default method is introduced in java 8 to add the new methods in the existing interfaces in such a way so that they are backward compatible. Backward compatibility is adding new features without breaking the old code.

Static methods in interfaces are similar to the default methods except that we cannot override these methods in the classes that implements these interfaces.

Читайте также:  Как задать расположение html

Java 8 Example: Default method in Interface

The method newMethod() in MyInterface is a default method, which means we need not to implement this method in the implementation class Example . This way we can add the default methods to existing interfaces without bothering about the classes that implements these interfaces.

interface MyInterface < /* This is a default method so we need not * to implement this method in the implementation * classes */ default void newMethod()< System.out.println("Newly added default method"); >/* Already existing public and abstract method * We must need to implement this method in * implementation classes. */ void existingMethod(String str); > public class Example implements MyInterface < // implementing abstract method public void existingMethod(String str)< System.out.println("String is: "+str); >public static void main(String[] args) < Example obj = new Example(); //calling the default method of interface obj.newMethod(); //calling the abstract method of interface obj.existingMethod("Java 8 is easy to learn"); >>
Newly added default method String is: Java 8 is easy to learn

Java 8 Example: Static method in Interface

As mentioned above, the static methods in interface are similar to default method so we need not to implement them in the implementation classes. We can safely add them to the existing interfaces without changing the code in the implementation classes. Since these methods are static, we cannot override them in the implementation classes.

interface MyInterface < /* This is a default method so we need not * to implement this method in the implementation * classes */ default void newMethod()< System.out.println("Newly added default method"); >/* This is a static method. Static method in interface is * similar to default method except that we cannot override * them in the implementation classes. * Similar to default methods, we need to implement these methods * in implementation classes so we can safely add them to the * existing interfaces. */ static void anotherNewMethod() < System.out.println("Newly added static method"); >/* Already existing public and abstract method * We must need to implement this method in * implementation classes. */ void existingMethod(String str); > public class Example implements MyInterface < // implementing abstract method public void existingMethod(String str)< System.out.println("String is: "+str); >public static void main(String[] args) < Example obj = new Example(); //calling the default method of interface obj.newMethod(); //calling the static method of interface MyInterface.anotherNewMethod(); //calling the abstract method of interface obj.existingMethod("Java 8 is easy to learn"); >>
Newly added default method Newly added static method String is: Java 8 is easy to learn

Java 8 – Abstract classes vs interfaces

With the introduction of default methods in interfaces, it seems that the abstract classes are same as interface in java 8. However this is not entirely true, even though we can now have concrete methods(methods with body) in interfaces just like abstract class, this doesn’t mean that they are same. There are still few differences between them, one of them is that abstract class can have constructor while in interfaces we can’t have constructors.

Читайте также:  Logged In

The purpose of interface is to provide full abstraction, while the purpose of abstract class is to provide partial abstraction. This still holds true. The interface is like a blueprint for your class, with the introduction of default methods you can simply say that we can add additional features in the interfaces without affecting the end user classes.

Default Method and Multiple Inheritance

The multiple inheritance problem can occur, when we have two interfaces with the default methods of same signature. Lets take an example.

interface MyInterface < default void newMethod()< System.out.println("Newly added default method"); >void existingMethod(String str); > interface MyInterface2 < default void newMethod()< System.out.println("Newly added default method"); >void disp(String str); > public class Example implements MyInterface, MyInterface2 < // implementing abstract methods public void existingMethod(String str)< System.out.println("String is: "+str); >public void disp(String str) < System.out.println("String is: "+str); >public static void main(String[] args) < Example obj = new Example(); //calling the default method of interface obj.newMethod(); >>
Error: Duplicate default methods named newMethod with the parameters () and () are inherited from the types MyInterface2 and MyInterface

This is because we have the same method in both the interface and the compiler is not sure which method to be invoked.

How to solve this issue?
To solve this problem, we can implement this method in the implementation class like this:

interface MyInterface < default void newMethod()< System.out.println("Newly added default method"); >void existingMethod(String str); > interface MyInterface2 < default void newMethod()< System.out.println("Newly added default method"); >void disp(String str); > public class Example implements MyInterface, MyInterface2 < // implementing abstract methods public void existingMethod(String str)< System.out.println("String is: "+str); >public void disp(String str) < System.out.println("String is: "+str); >//Implementation of duplicate default method public void newMethod() < System.out.println("Implementation of default method"); >public static void main(String[] args) < Example obj = new Example(); //calling the default method of interface obj.newMethod(); >>
Implementation of default method

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

Оцените статью