Default and static methods of Interface in Java 8 example


Java 8 Introduces interfaces with default and static methods

Interface:
package org.interfaces;

public interface MyInterface {
//Abstarct method
      public void printSomeThing();
     
       //static method
static void callMe() {
System.out.println(“Called Static method of My interface!”);
}
   
      //Default method
public default void dontCallMe() {
System.out.println(“Called Default method of My interface!”);
}
}

Impl:

package org.interfaces;
class MyImpl implements MyInterface {
// Default method is available we can override or leave it as it is.
//static method wont available we know that
// Implementation of abstract method
@Override
public void printSomeThing() {
System.out.println(“PrintSomthing Overrieden!”);
}
}
public class Demo {
public static void main(String[] args) {
MyImpl impl = new MyImpl();
// Calling default method
impl.dontCallMe();
// Normal impl of abstarcty method invocation
impl.printSomeThing();
// Calling static method of Interface directly
MyInterface.callMe();
}
}


Leave a Reply

Your email address will not be published. Required fields are marked *

Enable Notifications OK No thanks