Thursday 26 June 2014

Interface : Default Methods

Default methods enables to add new functionality to the existing interfaces, and ensure binary compatibility with code written for older versions of those interfaces.

By using default keyword you can specify a default implementation for a method in interface. All method declarations in an interface, including default methods, are implicitly public.

Example
interface Car{
 void swim();
 void drive();
}

class MyCar implements Car{
 public void swim(){
  System.out.println("I can swim");
 }
 
 public void drive(){
  System.out.println("I can Drive");
 }
}
Lets suppose, the Car interface adds new functionality like that all cars can fly.A new abstract method 'fly' added to Car interface like below.

interface Car{
 void swim();
 void drive();
 void fly();
}

Previously MyCar class implemented the Car interface, now with this updated version of Car interface, if you tries to compile MyClass.java, compiler throws below error since, MyCar is not providing implementation for 'fly'.

MyCar.java:1: error: MyCar is not abstract and does not override abstract method
 fly() in Car
class MyCar implements Car{
^
1 error

Here default methods plays a role to ensure binary compatibility with code written for older versions of those interfaces.

interface Car{
 void swim();
 void drive();
 default void fly(){
  System.out.println("I Can Fly");
 }
}

We are providing default implementation for the fly method in Car interface. So it makes your previously existed classes which implements Car interface works fine.

class MyCar implements Car{
 public void swim(){
  System.out.println("I can Swim");
 }
 
 public void drive(){
  System.out.println("I can Drive");
 }
}

class CarTest{
 public static void main(String args[]){
  MyCar car1 = new MyCar();
  
  car1.swim();
  car1.drive();
  car1.fly();
 }
}

Output
I can Swim
I can Drive
I Can Fly



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment