Implement multiple interfaces in java-7.4
This section describes another interface feature: multiple interfaces.
In normal cases, we only inherit one type of inheritance, but only one type of upward transformation can be achieved. However, in terms of Interface Usage, we can implement multiple interfaces and then implement various upward transformations.
Let's start with the code:
Package com. ray. ch07; public class Test {public static void testSwim (CanSwim canSwim) {canSwim. swim ();} public static void testEat (CanEat canEat) {canEat. eat ();} public static void testRun (CanRun canRun) {canRun. run ();} public static void main (String [] args) {Person person = new Person (); testSwim (person); // transition to CanSwimtestEat (person ); // transition to CanEattestRun (person); // transition to CanRunFish fish = new Fish (); testSwim (fish); // testEat (fish ); // error, because there is no implemented interface, it cannot be transformed up // testRun (fish); // error, because there is no implemented interface, cannot transition upwards} interface CanRun {void run ();} interface CanSwim {void swim ();} interface CanEat {void eat ();} class Person implements CanEat, CanRun, canSwim {@ Overridepublic void swim () {System. out. println (I can swim) ;}@ Overridepublic void run () {System. out. println (I can run) ;}@ Overridepublic void eat () {System. out. println (I can eat);} class Fish implements CanSwim {@ Overridepublic void swim () {System. out. println (I can swim );}}
Explain the above Code:
1. Three interfaces are created: Swimming, running, and eating.
2. Create a Person class to implement the above three interfaces
3. Create a Fish class, just implement the swimming Interface
4. Use the policy design mode in the test code to test the three skills.
In the code, Person is transformed to CanRun, CanSwim, and CanEat respectively, which greatly enhances the flexibility of the Code. Otherwise, we must add code in the test code, to complete the test. It is not conducive to code reuse. If CanSwim is not an interface, it becomes a base class, but its implementation may be inappropriate for Person or Fish, and the code may be ambiguous, but now it is an interface, just a protocol, indicating that the subclass only has a certain function, and how to implement this function, depending on the implementation of the subclass, so that the code can be reused more extensively.
Summary: This chapter describes multiple implementations of interfaces and their flexibility.