Java Interface Defaults

Java Interface and default methods

  • Default methods in a interface is a common implementation for all classes that implements it.
  • Classes can override default methods with their own implementation.
    Interface default method example:
    interface Radio {
      public boolean hasRadio();
      default public String containRadio() {
        return "The fact that the " + getClass().getSimpleName() + 
              " has a radio is " + hasRadio();
      }
    }
    class Cow implements Radio{
      @Override
      public boolean hasRadio() {
        return false;
      }
    }
    class Car implements Radio {
      @Override
      public boolean hasRadio() {
        return true;
      }
      @Override
      public String containRadio() {
        if (hasRadio()){return "This is a car that has a radio";}
        else {return "This is a car that has no radio";}
      }
    }
    public class InterfaceDefaultApp {
        public static void main(String[] args) {
        Radio carRadio=new Car();
        System.out.println(carRadio.containRadio());
        Radio cowRadio=new Cow();
        System.out.println(cowRadio.containRadio());
        }
    }
    
    The result of this is:
    This is a car that has a radio
    The fact that the Cow has a radio is false
    You can download this example here. (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.