Searching...
Saturday, 28 November 2015

Java 8 Default Method Example

17:21

Java 8 Default methods enable us to add new functionalities to interfaces without breaking the classes that implements that interface.

Here is one example, the Civic and Accord class implementing the same interface and one only Accord is the only class implementing the default method.

package com.vinod.test;

public interface Vehicle {
void printName(String name);

default public void printColor(String color) {
System.out.println(color);
}
}
package com.vinod.test;

public class Civic implements Vehicle{

@Override
public void printName(String name) {
System.out.println("I am Vehicle ...." + name);

}

}
package com.vinod.test;

public class Accord implements Vehicle {

@Override
public void printName(String name) {
System.out.println("I am Vehicle ...." + name);
}
@Override
public void printColor(String color) {
System.out.println("My color is ...." + color);
}

}
package com.vinod.test;

public class Java8DefaultMethodExample {

public static void main(String[] args) {
Vehicle civic = new Civic();
Vehicle accord = new Accord();
civic.printName("Civic");
accord.printName("Accord");
accord.printColor("White");

}

}


Output
I am Vehicle ....Civic
I am Vehicle ....Accord
My color is ....White

0 comments: