In this chapter, let's discuss the problem of adaptation.
To be blunt, it is possible to invoke a method with any object that only needs to conform to some kind of protocol.
There are two ways to implement this Protocol: inheritance and interface, but generally use interfaces, because his code reusability is stronger than inheritance, and inheritance itself contains many implementations of the parent class, causing unnecessary confusion. And through the interface we can implement multiple interfaces (like multiple inheritance)
Here are the two sets of code for comparison:
Package Com.ray.ch07;class Father {private int id = 0;private void sleep () {}public int run (int speed) {return speed;}} public class Test extends father {@Overridepublic int run (int speed) {//TODO auto-generated method Stubreturn Super.run (s peed);}}
Through inheritance, generally like the above code, test single-Inheritance Father,test objects can only be transformed upward into the Father class, if multiple inheritance is required, the level of inheritance may increase suddenly.
Let's take a look at the interface aspect:
Package Com.ray.ch07;interface Son {void sleep (); int run (int speed);} Interface mother {void Eat ();} public class Test implements Son, mother {@Overridepublic void Eat () {//TODO auto-generated method stub} @Overridepublic V OID sleep () {//Todo auto-generated method stub} @Overridepublic int run (int speed) {//Todo auto-generated method Stubretu RN 0;} public static void Main (string[] args) {Mother mother = new Test (); Mother.eat (); Son son = new Test (); Son.sleep (); Son.run (2);}}
In the above code, test can easily be transformed up to son and mother two classes, from a polymorphic point of view, the use of interfaces to adapt code reusability greatly increased, and the code more flexible.
Summary: This chapter focuses on which of the adaptation implementations to use, and we recommend using interfaces because he brings more flexibility and reusability of the code.
This chapter is here, thank you.
-----------------------------------
Directory
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
From the beginning to know java-7.6 adaptation design patterns exactly the right class? Or the adapter interface?