1 InterfaceInterfaceone2{3 voidSayHello ();4}5 / * Interface with extends keyword 6 interface Interfacetwo implements Interfaceone 7 { 8 9}*/Ten InterfaceInterfacethreeextendsInterfaceone One{ A} - //Abstract classes can not implement interfaces or methods of parent abstract classes. - Abstract classAbstractclassoneImplementsInterfaceone the{ -} - Abstract classAbstractclasstwoextendsAbstractclassone -{ +} - //non-abstract classes must implement methods within the interface. + classClassoneImplementsInterfaceone A{ at Public voidSayHello () {}; -}
If you encounter a number of methods that need to be implemented in an interface, we only need to use a few of these methods,
Assume that the interface that needs to inherit is:
1interface A 2 { 3void operation1 (); 4void operation2 (); 5 ... 6void operation100 (); 7 }
Let's say we just need to use one of the OPERATION5
If this interface is inherited directly, all methods are implemented:
1 classClassImplementsA2{3 Public voidOperation1 () {}4 Public voidOperation2 () {}5......6 Public voidOperation5 () {7 /* 8 * OPERATION5 9 * /Ten} One...... A Public voidOperation100 () {} -}
This is very cumbersome, so you can use the following methods to solve,
Create a new abstract class (if you specify an interface method to be implemented, set it as an abstract method, for example operation99 must be implemented):
1 Abstract classAbstractImplementsA2{3 Public voidOperation1 () {}4 Public voidOperation2 () {}5......6 Public voidOperation98 () {}7 //The operation99 here does not provide a virtual implementation, so it must be implemented in a specific class. 8 Public voidOperation100 () {}9}
To provide a virtual implementation for all interface methods, the future use of this interface only needs to do the following:
1 classClassextendsAbstract2{3 //Rewrite operation54 Public voidOperation5 () {5 /* 6 * operation5 7 * /8}9 //Implement Operation99Ten Public voidOperation99 () { One /* * operation99 * * -} the}
This eliminates the need to provide implementations for each interface method.
Summary of usage of implements and extends in Java