Up to Java 7
, it was nearly impossible to add new methods or functionality in Interface
due to backwards compatibility issues. Java 8
allows default
and static
methods in Interface
which will have an implementation in Interface
only. So from Java 8
onwards, Interfaces
supports 3
types of methods.
- abstract method
- default method
- static method
An abstract
method has declaration only, the implementing class will override the method and provide the definition.
Default
methods allow adding new functionality in the Interface
only which if required then can be overridden by implementing class.
Static
methods are part of the Interface
only and are bound with them, it cannot be overridden.
package org.wesome.dsalgo.java8;
interface Fruit {
/* normal abstract method */
void likedFruit(String appleName);
/* default method */
default void likedApple(String appleName) {
System.out.println("i love Apple, my favourite apple is " + appleName);
}
/* static method */
static void likedMango(String mangoName) {
System.out.println("i love Mango, my favourite mango is " + mangoName);
}
}
class Apple implements Fruit {
@Override
public void likedFruit(String fruitName) {
System.out.println("i love fruit, my favourite fruit is " + fruitName);
}
public static void main(String[] args) {
Fruit apple = new Apple();
apple.likedFruit("apple");
apple.likedApple("Fuji");
Fruit.likedMango("Alphonso");
}
}
some differences between static and default methods are
static method |
|
default method |
|
---|---|---|---|
1 |
static methods belong to the interface and cannot be override |
a default method can be overridden by implementing class |
|
2 |
a static method can be invoked using interface name only |
a default method can be invoked using the class instance |
|
3 |
the static method has a static prefix |
default method has a default prefix |
|
4 |
static methods are by default public |
default methods are by default public |
|
5 |
multiple inheritances create a diamond problem which is resolved using the super keyword. |
default method belongs to Interface so the diamond problem never arises. |
|
6 |
Interface and implementing class both can have the same name method< |
implementing class cannot have the same name method as the default method of the interface. |
|
7 |
Mostly used as a utility method |
mostly used for providing a default implementation |
with the introduction of static
and default
methods in Interface
, there is not much difference left between abstract class
and Interface
now except an abstract class
can have constructor
, variables
etc which Interface
cannot.
an implementing class
can extend
only 1 abstract
class where as can implement
any number of interfaces
required.