Java 8 Adds the default method for the interface.
Simply put, the default method is that the interface can have an implementation method, and does not need to implement the class to implement its methods.
We just need to add the default keyword to the method name to implement it.
Why do we have this feature?
First, the previous interface is a double-edged sword, and the advantage is that it is oriented toward abstraction rather than specific programming, and the drawback is that when you need to modify the interface, you need to modify all of the classes that implement the interface, and the current Java 8 Collection framework does not have a foreach method. The usual solution is to add new methods and implementations to the relevant interfaces in the JDK. However, for a released version, there is no way to add a new method to the interface without affecting the existing implementation. So introduce the default method. Their purpose is to solve the problem that the interface modification is incompatible with the existing implementation.
Example Demo:
1 /**2 * @author[email protected]3 * @version1.04 * @name5 * @description6 * @date 2018/7/157 */8 Public InterfaceVehicle {9 //default method in interfaceTen default voidprint () { OneSystem.out.println ("I'm a car!")); A } - //static methods in interfaces - Static voidBlowhorn () { theSYSTEM.OUT.PRINTLN ("Honk!")); - } -}
1 /**2 * @author[email protected]3 * @version1.04 * @name5 * @description6 * @date 2018/7/157 */8 Public InterfaceFourwheeler {9 Ten default voidprint () { OneSystem.out.println ("I'm a four-wheeled car!")); A } -}
/** * @author[email protected] *@version1.0 * @name * @description * @date 2018/7/15*/ Public classCarImplementsfourwheeler,vehicle{@Override Public voidprint () {//I'm a car!Vehicle.Super. Print (); //I'm a four-wheeled car!Fourwheeler.Super. Print (); //Press the Horn!Vehicle.blowhorn (); //I'm a car!System.out.println ("I'm a car!")); }}
1 /**2 * @author[email protected]3 * @version1.04 * @name5 * @description6 * @date 2018/7/157 */8 Public classTest4 {9 Public Static voidMain (String args[]) {Ten //Create an instance of car OneFourwheeler Fourwheeler =NewCar (); A //To perform a printing method - fourwheeler.print (); - } the}
JAVA8 new Features-Interface default method