Friday, 22 April 2016

Can a Java interface have method with body ?


Can a Java interface have method with body ?

Yes, It is possible in Java 8 , but not in earlier Java versions.

Java 8 allows to define 2 kind of methods with body in the interfaces : 
  1. default method : To add default implementation by using "default " keyword
  2. static methods : defined using "static" keyword and can be called directly by interface name

package com.genius;
interface MyInterface{ 
  abstract void add();

  default void display(){
    System.out.println("default method of interface");
  }

  public static void show(){
    System.out.println("static method of interface");
  }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.