Interface
- An interface is a group of methods that can be called by another object.
- An object can have multiple interfaces.
- Type is a special interface of an object
- Different objects can have the same type. An object can have multiple types.
- An object can only be known to other objects through its interface.
- Interfaces are the key to pluggable
Implement inheritance and interface inheritance
- Implementation inheritance (class inheritance) ------ the implementation Definition of one object is based on the implementation of another object
- Interface inheritance ------ describes when an object can be used instead of another object
- Java provides a dedicated structure for interface inheritance-Interface
- Java interface structure makes it easier to focus on the design of object interfaces.
Advantages and disadvantages of interfaces
- Advantages
- The client does not know the specific types of the objects they use.
- One object can be easily replaced by another object.
- Objects do not need to be hard connected to a special class object, so flexibility is increased.
- Loose coupling
- Increased the chance of reuse
- Added the opportunity for combination, because the contained object can be replaced by other objects that implement a specific interface.
- Disadvantages
- To some extent, the design complexity is increased.
Interface instance
/** <Br/> * interface imaneuverable provides the specification <br/> * For a maneuverable vehicle. <br/> */<br/> Public interface imaneuverable {<br/> Public void left (); </P> <p> Public void right (); </P> <p> Public void forward (); </P> <p> Public void reverse (); </P> <p> Public void climb (); </P> <p> Public void dive (); </P> <p> Public void setspeed (double speed ); </P> <p> Public double getspeed (); <br/>}</P> <p> public class car implements imaneuverable {<br/> // code here. <br/>}</P> <p> public class boat implements imaneuverable {<br/> // code here. <br/>}</P> <p> public class submarine implements imaneuverable {<br/> // code here. <br/>}
In the following method, you only need to know which type (CAR, boat, submarine) or hierarchy of the vehicle to which the parameter belongs.
Public void travel (imaneuverable vehicle) {<br/> vehicle. setspeed( 35.0); <br/> vehicle. forward (); <br/> vehicle. left (); <br/> vehicle. climb (); <br/>}
Summary
Using this principle can bring about more flexible design, because when we want to replace the implementation of a class, we do not need to change the originalCode.