Valid Java, inclutivejava

Source: Internet
Author: User

Valid Java, inclutivejava

Java has two mechanisms to provide multiple implementations for an abstraction --InterfaceAndAbstract class.


Interface and abstract class,
In addition to the obvious difference (that is, whether basic implementation can be provided ),
The important difference is that the implementation class of the interface can be at any position of the class level, while the subclass of the abstract class is subject to this restriction.

 

Existing classes can be easily retrofitted to implement a new interface.

That is, if a class needs to implement an interface, you only need to add the implements statement and method implementation.
Inheriting an abstract class may damage the class hierarchy. For example, when classes belonging to two different class levels want the behavior of an abstract class, we need to reorganize the class hierarchy.

 

Interfaces are ideal for defining mixins.

(The word "mixin" does not know how to translate. It seems stiff to translate it into "Mixed Type .)
I personally think this article is almost the same as the first article.
For mixin, the author uses Comparable as an example. Its implementation class indicates that your instance has the ability to compare with each other.
Abstract classes cannot be updated to existing classes at will. Considering the class hierarchy, it is more appropriate to provide classes with abstract behavior interfaces.

 

Interfaces allow the construction of nonhierarchical type frameworks.

In fact, class hierarchies are not useless, but we need to think about whether to organize them into strict hierarchies.
For example, do singers and composite require hierarchies? Obviously, they have no hierarchy.

That is:

public interface Singer{    AudioClip sing(Song s);}public interface Songwriter{    Song compose(boolean hit);}


For a creative artist, he needs to expand Singer and Songwriter at the same time.
Fortunately, both of them are interfaces, so we can:

public interface SingerSongwirter extends Singer, Songwriter{    AudioClip strum();    void actSensitive();}


If you try to use abstract classes to solve this problem,
Maybe we can use the object of a class as the field of another class,
Maybe we can also organize them into class hierarchies.
However, if the number of classes increases and more combinations emerge, the structure will become bloated (ps: called "combinatorial explosion ").


In addition, let's talk about the obvious "disadvantage" of the interface, that is, it cannot provide any implementation.
However, it should be noted that this feature cannot replace an abstract class with an interface.
It is common to use a better method to combine the two.
For example, the DefaultSecurityManager class hierarchy of Apache Shiro (of course, Shiro is still being improved ...):

 

 

That is, provide an abstract skeleton implementation (skeletal implementation) for the definition in the interface, and combine the advantages of the interface and the abstract class.

Generally, an abstract class provides the skeletal implementation for an interface, such as AbstractSet and Set, AbstractCollection, and Collection.

If I use this skeletal implementation, wouldn't I be troubled by the class hierarchy?
This is true, but skeletal does not mean flexibility.
First, let's take the code example in the book. The static factory method uses the skeletal class to return the integer list (ps: excessive use of automatic unpacking ...):

public class IntArrays {    static List<Integer> intArrayAsList(final int[] a) {        if (a == null)            throw new NullPointerException();        return new AbstractList<Integer>() {            public Integer get(int i) {                return a[i];             }            @Override            public Integer set(int i, Integer val) {                int oldVal = a[i];                a[i] = val;                 return oldVal;             }            public int size() {                return a.length;            }        };    }}


Another example in Apache Shiro is described in the org. apache. shiro. realm. Realm interface as follows:

Most users will not implement the Realm interface directly, but will extend one of the subclasses, {@link org.apache.shiro.realm.AuthenticatingRealm AuthenticatingRealm} or {@link org.apache.shiro.realm.AuthorizingRealm}, greatly reducing the effort requird to implement a Realm from scratch.


That is, it is tedious to directly implement an interface. We recommend that you use its subclass (of course, not required), for example:

org.apache.shiro.realm.CachingRealm CachingRealmorg.apache.shiro.realm.AuthenticatingRealm AuthenticatingRealmorg.apache.shiro.realm.AuthorizingRealm

Of course, there are also simple implementation classes, such:

org.apache.shiro.authc.pam.ModularRealmAuthenticator


The following is an example of skeletal writing in the book:

public abstract class AbstractMapEntry<K, V> implements Map.Entry<K, V> {    // Primitive operations    public abstract K getKey();    public abstract V getValue();    // Entries in modifiable maps must override this method    public V setValue(V value) {        throw new UnsupportedOperationException();    }    // Implements the general contract of Map.Entry.equals    @Override    public boolean equals(Object o) {        if (o == this)            return true;        if (!(o instanceof Map.Entry))            return false;        Map.Entry<?, ?> arg = (Map.Entry) o;        return equals(getKey(), arg.getKey())                && equals(getValue(), arg.getValue());    }    private static boolean equals(Object o1, Object o2) {        return o1 == null ? o2 == null : o1.equals(o2);    }    // Implements the general contract of Map.Entry.hashCode    @Override    public int hashCode() {        return hashCode(getKey()) ^ hashCode(getValue());    }    private static int hashCode(Object obj) {        return obj == null ? 0 : obj.hashCode();    }}


As opposed to providing an implementation class, writing a skeletal implementation has some limitations.
First, you must understand what is the most basic behavior in the interface and leave its implementation to the subclass implementation. skeletal is responsible for other methods in the interface (or none) or its feature-related implementations.
In addition, the value of the skeletal Class lies in inheritance. If you do not pay attention to it, the encapsulation may be damaged due to inheritance.
The classes designed for inheritance also need to provide relevant documents, such as which methods are self-use and the class implements Serializable or Clonnable...


In addition to providing basic implementation advantages, abstract classes are easier to change than interfaces.
That is, adding methods to abstract classes in subsequent versions is easier than adding methods to interfaces.
It is impossible to add a method to a public interface without damaging the implementation class (even if the following is a skeletal class, there will always be an implementation class after being detached ).
Therefore, designing an interface is a technical activity. Once it is set, you don't want to change it any more.


The choice between an abstract class and an interface is a choice between scalability and flexibility.

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.