Monday, 6 March 2017

Default and Static Method in Interface

Default and Static method in interface is also a one of the inportant fetaure of Java 8. Before Java 8 interfaces only containes abstract method with only method declaration. But from Java 8 interfaces containes default and static method with method body.

Interface With default method :
For creating default method in Java 8 ,we have to use default keyword before the method signature. As shown below

1
2
3
4
5
6
7
interface Car{
 void BMW(); // Abstract Method
 
 default void Audi(){ // Default Method
  System.out.println("Default Method in Interface");
 }
}

Interface With static method :
For creating static method in Java 8 ,we have to use static keyword before the method signature. As shown below

1
2
3
4
5
6
7
interface Car{
 void BMW(); // Abstract Method
 
 static void Audi(){ // Static Method
  System.out.println("Static Method in Interface");
 }
}

Example:
Complete example of default and static method is shown below :

 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
33
34
35
36
37
38
39
40
interface Audi{
 void show();
 default void defaultMethod(){
  System.out.println("DEFAULT INTERFACE METHOD OF AUDI ");
 }
 static void AUDIstaticMethod(){
  System.out.println("STATIC METHOD OF AUDI");
 }
}
interface BMW{
 default void defaultMethod(){
  System.out.println("DEFAULT INTERFACE METHOD OF BMW ");
 }
 static void BMWstaticMethod(){
  System.out.println("STATIC METHOD OF BMW");
 }
}
class Vehicle implements Audi,BMW{

 @Override
 public void show() {
  // TODO Auto-generated method stub
 }
 @Override
 public void defaultMethod() {
  // TODO Auto-generated method stub
  Audi.super.defaultMethod();
  Audi.AUDIstaticMethod();
  BMW.super.defaultMethod();
  BMW.BMWstaticMethod();
 }
}
public class DefaultAndStaticMethodInInterfaces {
 
 public static void main(String[] args) {
  Audi c = new Vehicle();
  c.defaultMethod();
 }

}

Output:

DEFAULT INTERFACE METHOD OF AUDI 
STATIC METHOD OF AUDI
DEFAULT INTERFACE METHOD OF BMW 
STATIC METHOD OF BMW


      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



No comments:

Post a Comment