In this chapter, let's take a look at the interface another feature: multiple interfaces.
In the ordinary, using inheritance, we just inherit a certain class, can only one kind of upward transformation, but in the use of the interface, you can implement multiple interfaces, and then achieve a variety of upward transformation.
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);//change upward to canswimtesteat (person);// Transition upward to Caneattestrun (person),//up to canrunfish fish = new Fish (), testswim (fish),////testeat (fish),//error, because no interface is implemented, cannot be transformed upward//testrun (fish);//error, because no interface is implemented, cannot be transformed upward}}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. Established three interfaces: can swim, will run, will eat
2. Create a person class to implement the above three interfaces
3. Build a fish class, just implement the swimming interface
4. Then use the strategy design pattern in the test code to test three skills
In the code, the person is transformed upward into the three types of Canrun, Canswim, Caneat, which greatly enhances the flexibility of the code, otherwise we have to add code in the test code to be able to complete the test. And it is not conducive to the reuse of code, if canswim this is not an interface, he became a base class, but his implementation may be for person or fish is not appropriate, and the code may be ambiguous, but now is the interface, is only a protocol, the subclass only has a certain function, And how this function is implemented, specifically needs to be based on the implementation of subclasses, so that the code is more widely reusable.
Summary: This chapter focuses on the multiple implementations of the interface, as well as his flexibility.
This chapter is here, thank you.
-----------------------------------
Directory
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Meet java-7.4 from the beginning to implement multiple interfaces