Java Interface Default Methods

Introduction

An interface default method is preceded by the keyword default.

For example, consider this simple interface:

public interface MyIF { 
  // a "normal" interface method declaration. 
  int getNumber(); 
 
  // a default method. 
  default String getString() { 
    return "Default String"; 
  } 
}

getString() is a default method, an implementing class need not to override it.

// Implement MyIF. 
class MyIFImp implements MyIF { 
  // we have to implement getNumber() defined by MyIF
  // getString() can be allowed to default. 
  public int getNumber() { 
    return 100; 
  } 
}

The following code creates an instance of MyIFImp and uses it to call both getNumber() and getString().


interface MyIF {/*from   w w  w . j  a  v a 2 s.c o  m*/
  // a "normal" interface method declaration.
  int getNumber();

  // a default method.
  default String getString() {
    return "Default String";
  }
}

class MyIFImp implements MyIF {
  // we have to implement getNumber() defined by MyIF
  // getString() can be allowed to default.
  public int getNumber() {
    return 100;
  }
}

class MyIFImp2 implements MyIF {
  // implementations for both getNumber() and getString() are provided.
  public int getNumber() {
    return 100;
  }

  public String getString() {
    return "This is a different string.";
  }
}

// Use the default method.
public class Main {
  public static void main(String args[]) {

    MyIFImp obj = new MyIFImp();

    // Can call getNumber(), because it is explicitly
    // implemented by MyIFImp:
    System.out.println(obj.getNumber());

    // Can also call getString(), because of default
    // implementation:
    System.out.println(obj.getString());

    MyIFImp2 obj2 = new MyIFImp2();

    System.out.println(obj2.getNumber());

    System.out.println(obj2.getString());
  }
}



PreviousNext

Related