- Java interface static method is similar to default method except that we can’t override them in the implementation classes.
- They are part of interface, we can’t use it for implementation class objects.
- It helps in providing security by not allowing implementation classes to override them.
- Interface static methods by-default not available to the implementation classes hence by using implementation class reference we can’t call interface static Method.
- We should call interface static methods by using interface name.
Example 1.
interface Static
{
public static void sum(int a, int b)
{
System.out.println("The
Sum:"+(a+b));
}
}
class Test implements Static{
public static void
main(String[] args)
{
Test
t = new Test();
t.sum(10, 20);
//Compile Time Error
Test.sum(10, 20); // Compile Time Error
Static.sum(10, 20);
}
}
}
}
Example 2.
interface Static{
public static void m1()
{} }
class Test implements Static{
public static void m1() {} }
It’s
valid but not overriding
Example 3.
interface Static
{
public static void m1() {}
public static void m1() {}
}
class Test implements Static
{
{
public void m1() {}
}
This’s valid but not overriding
Example 4.
class P{
private void m1() {}
}
class C extends P {
public void m1() {}
}
This’s valid but not overriding
From 1.8 version onwards we can write main() method inside
interface and hence we can run interface
directly from the command prompt.
Example : 5
interface Static{
public static void main(String[] args)
{
System.out.println("Interface Main Method");
}
What a nice blog to learn java 8! Kudos to your efforts :)
ReplyDeleteThanks for appreciation.
Delete