In Java 8 we were able to use method implementation in
interfaces as default methods. But the private methods were missing in Java 8
when the default method is added. So now
that both default and private methods can exist within an interface. Before we
are going to the details we can check the changes came for the interfaces in
the previous versions
Static Methods
Java 7
In Java 7 we can provide only two things in interfaces
- · Constant variables
- · Abstract methods
Example:
public interface
SampleInterface_7 {
String
CONSTANT_1 = "CONSTANT_1";
public void method1();
}
Java 8
In Java 8 we can provide following things in interfaces
- · Constant variables
- · Abstract methods
- · Default methods
- · Static methods
Default Methods
We need to use ‘default’ keyword with the signature to use
the default method in interface. If we define a default method in interface, it
is not mandatory to provide implementation for the default method. If two interfaces have same default methods
and if a class implementing both interfaces, then compiler will not be able to
choose which method is to choose. Hence it’s mandatory to provide the
implementation for the default method in this scenario.
Static Methods
Static methods are similar to default methods, but cannot override
in the implementation classes.
Example:
public interface
SampleInterface_8 {
String
CONSTANT_1 = "CONSTANT_1";
public void method1();
default void
default_method() {
System.out.println("This is
default method");
}
public static void method2() {
System.out.println("This is
a public static method");
}
}
Java 9
In Java 9 an interface can have six kinds of things
- · Constant variables
- · Abstract methods
- · Default methods
- · Static methods
- · Private methods
- · Private Static methods
‘abstract’ keyword cannot use with private methods. Private
methods can be used only inside interfaces. And it can be used inside the
static and non-static interface methods.
Example :
public interface
SampleInterface_9 {
String CONSTANT_1 = "CONSTANT_1";
public void method1();
default void
default_method() {
System.out.println("This is
default method");
/**
* Private method
can be called from default method
*/
method3();
}
public static void method2() {
System.out.println("This is
a public static method");
/**
* Static method
can be called from static method
*/
method4();
}
private void method3() {
System.out.println("This is
private interface method");
}
private static void method4() {
System.out.println("This is
private static interface method");
}
}
Sample Code is available at
Comments
Post a Comment