Java_8 New - Default Methodsava 8 introduces a new concept of default method implementation in interfaces. This capability is added for backward compatability so that old interfaces can be used to leverage lambda expression capability of JAVA 8. For example List or Collection interfaces do not have forEach method declaration. Thus adding such method will simply break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implemenation of forEach method and class implementing these interfaces need not to implement the same. Syntax
publicinterface vehicle {
defaultvoidprint(){ System.out.println("I am a vehicle!"); } } Multiple Defaults With default functions in interfaces, their is a quite possibility that a class implementing two interfaces with same default methods then how to resolve that ambiguity. Consider the following case.
publicinterface vehicle {
defaultvoidprint(){ System.out.println("I am a vehicle!"); } } publicinterface fourWheeler { defaultvoidprint(){ System.out.println("I am a four wheeler!"); } } First solution is to create an own method which overrides the default implementation.
publicclass car implements vehicle, fourWheeler {
defaultvoidprint(){ System.out.println("I am a four wheeler car vehicle!"); } } Second solution is to call the default method of the specified interface using super.
publicclass car implements vehicle, fourWheeler {
defaultvoidprint(){ vehicle.super.print(); } } Static default methods Now interface can also have static helper methods as well from Java 8 onwards.
publicinterface vehicle {
defaultvoidprint(){ System.out.println("I am a vehicle!"); } staticvoid blowHorn(){ System.out.println("Blowing horn!!!"); } } Default method Example Create the following java program using any editor of your choice in say C:/> JAVA Java8Tester.java
publicclassJava8Tester{
publicstaticvoid main(String args[]){ Vehicle vehicle =newCar(); vehicle.print(); } } interfaceVehicle{ defaultvoidprint(){ System.out.println("I am a vehicle!"); } staticvoid blowHorn(){ System.out.println("Blowing horn!!!"); } } interfaceFourWheeler{ defaultvoidprint(){ System.out.println("I am a four wheeler!"); } } classCarimplementsVehicle,FourWheeler{ publicvoidprint(){ Vehicle.super.print(); FourWheeler.super.print(); Vehicle.blowHorn(); System.out.println("I am a car!"); } } Verify the result Compile the class using javac compiler as follows
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester to see the result
C:\JAVA>java Java8Tester
See the result.
I am a vehicle!
I am a four wheeler! Blowing horn!!! I am a car! |