Java interfaces and abstract class differences

Source: Internet
Author: User
Tags naming convention

Original: http://blog.csdn.net/sunboard/article/details/3831823

1. Overview

A software design is good or bad, I think very much depends on its overall architecture, and this overall architecture is in fact your entire macro business of the abstract framework, when the high-level abstraction layer representing business logic is reasonable, you need to consider the underlying detailed implementation of some algorithms and some detailed business implementation. When you need to develop a similar project, you may be able to use the abstraction layer again. in the face of object design, the emphasis of reuse should actually be the reuse of the abstraction layer, rather than the reuse of a code block in detail .

When it comes to abstraction, I can't help but mention the Java interface and Java abstraction classes that have made me headache, which is what I want to say in this article.

Since the focus of object-oriented design is on abstraction, the Java interface and Java abstract classes have the certainty of its existence.

The Java Interface (interface) and the Java abstract class represent abstract types, which are the detailed representations of the abstraction layers that we need to propose. OOP object-oriented programming, if you want to improve the reuse rate of programs, add program maintainability, extensibility, it must be interface-oriented programming, oriented to abstract programming, the proper use of interfaces, abstract classes of these practical abstract types as the top layer of your structure.

There are so many similarities between Java interfaces and Java abstract classes, and there are so many special places, where exactly is the best place for them? Compare them and you'll be able to find out.

  1. One of the biggest differences between Java interfaces and Java abstract classes is that Java abstract classes can provide partial implementations of some methods, while Java interfaces cannot (that is, only the methods can be defined in interface, not the implementation of methods, but in the abstract Class can have both a detailed implementation of the method, and there is no detailed implementation of the abstract method, which is probably the only advantage of Java abstract class, but this advantage is very practical. Assuming that a new detailed method is added to an abstract class, then all of its subclasses get the new method at once, and the Java interface does not do this, assuming that a new method is added to a Java interface, and that all the classes that implement the interface cannot be compiled successfully. Since you have to have each class implement this method again, this is obviously a disadvantage of the Java interface . This is a similar issue in one of my other blog MapReduce new and old API differences, which in the new MapReduce API tends to use abstract classes rather than interfaces, as this is easier to extend. The reason is that the underlined part says.
  2. The implementation of an abstract class can only be given by subclasses of this abstract class, that is, the implementation is in the hierarchy of inheritance defined by the abstract class, and because of the single inheritance of the Java language, the efficiency of the abstract class as a type definition tool is greatly compromised. At this point, the advantages of the Java interface come out, no matter what a Java interface to implement a method specified by the class can have the type of the interface, and a class can implement arbitrary multiple Java interfaces, so that the class has a variety of types. (using abstract classes, the subclass type of inheriting this abstract class is relatively simple, because subclasses can simply inherit abstract classes, and subclasses can implement multiple interfaces at the same time, because the type is much more.) Interfaces and abstract classes are able to define objects, but they can only be instantiated with their detailed implementation classes. )
  3. From the 2nd, it is not difficult to see that Java interfaces are an ideal tool for defining mixed types, and mixed classes indicate that a class does not only have the behavior of one of the main types, but also has other minor behaviors.
  4. Combining the advantages of abstract class and Java interface in 1, 2 points, the design pattern of the refined code comes out: the work of declaring type is still assumed by the Java interface, but at the same time a Java abstract class is given, and this interface is implemented. While other classes of this abstract type can choose to implement this Java interface, you can choose to inherit this abstract class, that is, in the hierarchy, the Java interface at the top, followed by the abstract class , the next two of the greatest strengths can play to the extreme. This mode is "default adaptation mode ". This pattern is used in the Java language API, and all follow a certain naming convention: Abstract + interface name. (a extends ABSTRACTB implements INTERFACEC, then a can choose to implement (@Override) interface Interfacec in the method, but also can choose not to implement; A is able to choose the implementation (@Override) Abstract class Abstractb method, also can choose not to implement)

Java interfaces and Java abstract classes exist to be used for the implementation and inheritance of detailed classes, assuming you are going to write a detailed class to inherit and a detailed class, then your design has a very big problem. The Java abstract class exists for inheritance, and its abstract approach is to force subclasses to be implemented.

Use Java interfaces and abstract Java classes to declare variables, type declarations, return type descriptions of methods, conversions of data types, and so on. Instead of using detailed Java classes for variable type declarations, arguments are type declarations, method return type descriptions, and data type conversions.

2. Example

The following gives a detailed interface to the action, as seen in the following code:

Package Org.springframework.webflow.execution;public interface Action {public Event Execute (requestcontext context) Throws Exception;}
In this interface, a method with no detailed implementation is defined, the method name is execute (), and the return type is event. As mentioned in the first article above, the methods in the interface are not implemented. The detailed implementation of these methods is given in the class that implements (implements) this interface.

Let's look at an abstract class abstractaction that implements the action interface, such as the following code.

Package Org.springframework.webflow.action;import Org.apache.commons.logging.log;import Org.apache.commons.logging.logfactory;import org.springframework.beans.factory.BeanInitializationException; Import Org.springframework.beans.factory.initializingbean;import Org.springframework.util.classutils;import Org.springframework.webflow.core.collection.attributemap;import org.springframework.webflow.execution.Action; Import Org.springframework.webflow.execution.event;import Org.springframework.webflow.execution.RequestContext; Public abstract class AbstractAction implements Action, Initializingbean {protected final Log logger = Logfactory.getlog (g Etclass ());p ublic eventfactorysupport Geteventfactorysupport () {return new Eventfactorysupport (); public void Afterpropertiesset () throws Exception {try {initaction ();} catch (Exception ex) {throw new Beaninitializatione Xception ("Initialization of this Action failed:" + ex.getmessage (), ex);}} protected void Initaction () throws Exception {}protected EveNT success () {return Geteventfactorysupport (). Success (this);} Protected Event Success (Object result) {return Geteventfactorysupport (). Success (this, result);} Protected Event Error () {return geteventfactorysupport (). Error (this);} Protected Event Error (Exception e) {return geteventfactorysupport (). Error (this, e);} Protected Event Yes () {return Geteventfactorysupport (). Yes (this);} Protected Event No () {return Geteventfactorysupport (). No (this);} Protected event Result (Boolean Booleanresult) {return Geteventfactorysupport (). Event (this, booleanresult);} Protected event Result (String eventId) {return Geteventfactorysupport (). Event (this, eventId);} Protected event Result (String eventId, AttributeMap resultattributes) {return Geteventfactorysupport (). event (This, EventId, resultattributes);} Protected Event Result (string eventId, String resultattributename, Object resultattributevalue) {return Geteventfactorysupport (). Event (this, EventId, Resultattributename, resultattributevalue);} Public final Event EXECute (RequestContext context) throws Exception {Event result = Dopreexecute (context); if (result = = null) {result = Doexecut E (context);d Opostexecute (context);} else {if (logger.isinfoenabled ()) {logger.info ("Action execution disallowed; Pre-execution result is ' "+ result.getid () +" ' ");}} return result;} Protected String getactionnameforlogging () {return classutils.getshortname (GetClass ());} Protected Event Dopreexecute (RequestContext context) throws Exception {return null;} Abstract method protected Abstract Event Doexecute (RequestContext context) throws exception;protected void Dopostexecute ( RequestContext context) throws Exception {}}
In abstract class abstractaction, there is both a detailed implementation method and an abstract method without detailed implementation.

Abstract method protected Abstract Event Doexecute (RequestContext context) throws Exception;
It is important to note that in an abstract class, it is assumed that the method is not implemented in detail (just after the method No {}), you must add an abstract to declare this method, and the interface does not need to use abstract to declare (an abstract class is called an abstract class because it includes an abstract method.) Classes containing abstract methods are called abstract classes)




Java interfaces and abstract class differences

Related Article

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.