Static methods are introduced in Java 8, just like default methods. If you don't know about interface default methods, read it first here.
Static methods are similar to default methods except that they cannot be overridden in their implementing classes.
Let’s take an example:
Let’s take an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public class StaticInterfaceExample implements MyInterface { public static void main(String args[]) { StaticInterfaceExample obj = new StaticInterfaceExample(); obj.getTrimmedString(" Java Territory "); obj.isNullOrEmpty("Java Territory"); } public boolean isNullOrEmpty(final String str) { System.out.println("Interface Null Check"); return str.isEmpty(); } } interface MyInterface { static boolean isNullOrEmpty(final String string) { System.out.println("Inside isNullOrEmpty MyInterface"); return (string == null || string.isEmpty()) ? true : false; } default String getTrimmedString(String string) { String trimmedText = null; if (!isNullOrEmpty(string)) { System.out.println("Inside getTrimmedString MyInterface"); trimmedText = string.trim(); } return trimmedText; } } |
Their are two implementations of isNullOrEmpty method, one in interface and one in implementing class.
What output do we get on executing above code? It's:
Inside isNullOrEmpty MyInterface Inside getTrimmedString MyInterface Inside isNullOrEmpty StaticInterfaceExample |
Its important to note here that isNullOrEmpty(final String string) is not overriding the interface method. Compiler error would be generated if we add @Override annotation to the isNullOrEmpty(final String string) method in StaticInterfaceExample.
If we make the interface method from static to default, we will get following output.
Inside isNullOrEmpty StaticInterfaceExample Inside getTrimmedString MyInterface Inside isNullOrEmpty StaticInterfaceExample |
The static methods are visible to interface methods only, if we remove the isNullOrEmpty method from the StaticInterfaceExample class, we won’t be able to use it for the StaticInterfaceExample object.
However like other static methods, we can use interface static methods using class name. For example, a valid statement will be:
boolean
isNullOrEmpty =
MyInterface.isNullOrEmpty ("abc"
);
Points to remember:
- Interface static methods are visible within interface only, they can't be used by implementation class objects.
- They can be used for utility methods.
- They secure the application by not allowing implementation classes to override them.
- They cant be overridden by implementing classes. Compile time error would get generated if any one try to do so.
Hope you liked the post. Join at +Java Territory to stay updated with latest articles.
0 comments:
Post a Comment