Read the Chinese version of objective Java (17)

Source: Internet
Author: User
Read the Chinese version of objective Java (17)

Article 14: interfaces are better than abstract classes

Some differences between interfaces and abstract classes in Java:

    • Abstract classes allow the implementation of some methods, and interfaces are not allowed.
    • To implement a type defined by an abstract class, it must be a subclass of the abstract class. Any class, as long as it defines all the required methods and complies with General Conventions, allows it to implement an interface.
    • Java only supports single inheritance. abstract classes are severely restricted as Type Definitions.

Take a look at the interface:

  1. Existing classes can be easily updated to implement new interfaces. As long as: add the required method, add the implements clause to the class declaration.
  2. The interface is an ideal choice for defining Mixin (mixed type. A Mixin refers to this type: in addition to its basic type (primary type), a class can also implement this Mixin type to indicate that it provides certain optional behaviors. The interface can define Mixin because it allows optional functions to be mixed into a basic type, and abstract classes cannot be used to define the Mixin type, the same reason is that they cannot be updated to an existing class: A class cannot have more than one parent class, and there is no proper place to place Mixin in the class hierarchy.

    Interface allows us to construct a non-hierarchical structure. Example:

    Public interface singer {

    Audioclip sing (Song S );

    }

    Public interface songwriter {

    Song compose (Boolean hit );

    }

    To solve the problem that a singer can also make a song, you can easily do the following:

    Public interface singersongwriter extends singer, songwriter {

    Audioclip strum ();

    Void actsensitive ();

    }

    What if I use abstract classes?
  3. The interface makes it possible to securely enhance a class-1 function by using the packaging mode described in Article 1. If the abstract type is usedProgramThere are no other methods except inheritance.
  4. The interface cannot contain methods. Combine the advantages of interfaces and abstract classes. For each important interface to be exported, an abstract skeleton implementation (skeletal implementaion) class is provided. The interface is still a defined type, and the skeleton implementation class is responsible for all work related to the interface implementation. The skeleton implementation is called abstractinterface (Note: This interface is the name of the implemented interface, such as abstractlist and abstractset ). Look at a static Factory:

    // List adapter for int Array

    Static list intarrayaslist (final int [] ){

    If (A = NULL) throw new nullpointerexception ();

    Return new effecactlist (){

    Public object get (int I ){

    Return new INTEGER (A [I]);

    }

    Public int size (){

    Return A. length;

    }

    Public object set (int I, object O ){

    Int oldval = A [I];

    A [I] = (integer) O). intvalue ();

    Return new INTEGER (oldval );

    }

    }

    }

    In this example, an adapter allows an int array to be considered as an integer instance list (the conversion between int and integer causes poor performance)

    Apart from the beauty of skeleton implementation, they provide implementation help for abstract classes, but do not impose strict restrictions that are specific to "When abstract classes are used for type definition. For most implementations of a single interface, the extension skeleton implementation class is a clear choice, and of course it is only a choice.

    The class implementing this interface can forward the call to the interface method to an instance of an internal private class, and this internal private class extends the skeleton implementation class. This technology is called multi-inheritance simulation.

    Compiling a skeleton implementation class is relatively simple. First, you must carefully study the interfaces and determine which methods are the most basic (primitive). Other methods will be based on them during implementation, these methods will be the abstract methods in the implementation class of the skeleton, and then the specific implementation must be provided for other methods in the interface. The skeleton implementation class is not designed for the purpose of inheritance. (How to Understand ?) Example:

    // Skeletal implementation

    Public abstract class abstractmapentry implements map. Entry {

    // Primitives

    Public abstract object getkey ();

    Public abstract object getvalue ();

    // entries in modifiable maps must override this method
    Public object setvalue (object Value) {
    throw new unsupportedoperationexception ();

    }< br>
    // implements the general contract of map. entry. equals
    Public Boolean equals (Object O) {
    If (O = This) return true;
    If (! (O instanceof map. entry) return false;
    map. entry Arg = (map. entry) O;
    return eq (getkey (), Arg. getkey () & eq (getvalue (), Arg. getvalue ();

    }< br>
    Private Static Boolean eq (Object O1, object O2) {
    return (O1 = NULL? 02 = NULL: o1.equals (O2);

    }< br>
    // implements the general contract of map. entry. hashcode
    Public int hashcode () {
    return (getkey () = NULL? 0: getkey. hashcode () ^ (getvalue () = NULL? 0: getvalue (). hashcode ();

    }

Using abstract classes to define the types that allow multiple implementations has a significant advantage over Using Interfaces: abstract classes are much easier to evolve than interfaces. In subsequent releases, if you want to add a method to the abstract class and add only one reasonable default implementation, all the implementations of the abstract class will automatically provide this new method. This is not feasible for interfaces. Although a method can be added to the skeleton implementation class to solve some problems, this cannot solve the problem of interface implementation that does not inherit from the skeleton implementation class. Therefore, you must be cautious when designing public interfaces. Once an interface is made public and widely implemented, it is impossible to modify it.

Posted by Hilton at February 16,200 4 pm | trackback

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.