As of Java 8 the interface definition can include implemented methods that will be used as the default implementation when a class that implements an interface doesn’t implement the methods. The default methods provide us with a mechanism for extending the interfaces mechanism in a backward compatible way.

In order to implement a method defined in our interface we just need to add the default keyword to the method definition.

The following code sample includes the definition for the IPrintable interface. The IPrintable interface includes the default implementation for the printStar method. Having a software system that already includes the IPrintable interface without any default implementation for any of its methods, adding default implemented methods won’t break the backward compatability in the context of those classes that were already defined as class that implement the IPrintable interface.

package com.lifemichael.samples; 

interface IPrintable
{
 public abstract void print();
 default public void printStar()
 {
 System.out.print("*");
 }
}

class Circle implements IPrintable
{
 private double radius;
 public Circle(double number)
 {
   setRadius(number);
 }
 public void setRadius(double num)
 {
   if(num>0)
   {
     radius = num;
   }
 }
 public void printStar()
 {
   System.out.println("x");
 }
 public void print()
 {
   System.out.println(" radius="+radius+" ");
 }
}

class Rectangle implements IPrintable
{
 private double width;
 private double height;
 public Rectangle(double w, double h)
 {
   setWidth(w);
   setHeight(h);
 }
 public void setWidth(double num)
 {
   if(num>0)
   {
     width = num;
   }
 }
public void setHeight(double num)
 {
   if(num>0)
   {
     height = num;
   }
 }
 public void print()
 {
   System.out.print(" width="+width+" height="+height+" ");
 }
}

public class Main 
{
  public static void main(String[] args) 
  {
    IPrintable ob = new Rectangle(4,3);
    ob.printStar();
    ob.print();
    ob.printStar();
  }
}

The following video clip overviews this code sample, shows its execution and explains each and every part of it.

You can find more video clips, tutorials and code samples for learning the new features in Java 8 in my free online courses at http://abelski.lifemichael.com.

Leave a Reply

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