Java interfaces and abstract class differences

Source: Internet
Author: User

Label:

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

1. Overview

A software design is good or bad, I think to a large extent, it depends on its overall structure, and this whole structure is your abstract framework of the entire macro-business business, when the high-level abstraction layer representing business logic is reasonable, your underlying implementation needs to consider only some algorithms and some specific business implementation. When you need to develop another similar project, your previous abstraction layer might be able to use it again. In the face of object design, the emphasis of reuse should be the reuse of abstraction layer, rather than the reuse of a specific code block .

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 object-oriented design focuses on abstraction, the Java interface and Java abstract classes have the inevitability of its existence.

The Java Interface (interface) and the Java abstract class represent abstract types, which are the concrete manifestations of the abstraction layer we need to propose. OOP object-oriented programming, if you want to increase the reuse rate of programs, increase the maintainability of the program, extensibility, it must be interface-oriented programming, for abstract programming, the correct use of interfaces, abstract classes, these useful abstract types as the top layer of your hierarchy.

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 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 methods can be defined in the interface, but not the implementation of methods, but in the abstract Class can have both the specific implementation of the method, and there is no concrete implementation of the abstract method, which is probably the only advantage of Java abstract class, but this advantage is very useful. If you add a new concrete method to an abstract class, all of its subclasses get the new method all of a sudden, and the Java interface does not do this, and if a new method is added to a Java interface, all classes that implement the interface will fail to compile successfully. Because you have to let every 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, where the new MapReduce API tends to use abstract classes rather than interfaces because it's 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 that any class that implements a method specified by a Java interface can have the type of this interface, and a class can implement any number of Java interfaces, so there are many types of this class. (with abstract classes, the subclass type that inherits this abstract class is relatively single, because subclasses can only inherit abstract classes, whereas subclasses can implement multiple interfaces at the same time because the types are more numerous.) Interfaces and abstract classes can define objects, but only their specific implementation classes are instantiated. )
  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 it gives a Java abstract class, and implements this interface, and other specific classes belonging to this abstract type can choose to implement this Java interface , you can also 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 advantage can be played 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, you can choose not to implement; a you can choose to implement (@Override) Abstract class Abstractb method, can also choose not to implement)

Java interfaces and Java abstract classes exist to be used for the implementation and inheritance of specific classes, and if you are going to write a specific class to inherit another specific class, then your design has a 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 for variable type declarations, arguments for type declarations, method return type descriptions, and conversion of data types. Instead of using specific Java classes to declare variable types, arguments are type declarations, method return type descriptions, and data type conversions.

2. Example

Here is a specific interface action, as shown in the code below:

[Java]View Plaincopy
    1. Package org.springframework.webflow.execution;
    2. Public interface Action {
    3. Public Event Execute (requestcontext context) throws Exception;
    4. }

In this interface, a method with no concrete 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 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, as shown in the code below.

[Java]View Plaincopy
  1. Package org.springframework.webflow.action;
  2. Import Org.apache.commons.logging.Log;
  3. Import Org.apache.commons.logging.LogFactory;
  4. Import org.springframework.beans.factory.BeanInitializationException;
  5. Import Org.springframework.beans.factory.InitializingBean;
  6. Import Org.springframework.util.ClassUtils;
  7. Import Org.springframework.webflow.core.collection.AttributeMap;
  8. Import org.springframework.webflow.execution.Action;
  9. Import org.springframework.webflow.execution.Event;
  10. Import Org.springframework.webflow.execution.RequestContext;
  11. Public abstract class AbstractAction implements Action, Initializingbean {
  12. protected Final Log logger = Logfactory.getlog (GetClass ());
  13. Public Eventfactorysupport Geteventfactorysupport () {
  14. return new Eventfactorysupport ();
  15. }
  16. public void Afterpropertiesset () throws Exception {
  17. try {
  18. Initaction ();
  19. } catch (Exception ex) {
  20. throw New Beaninitializationexception ("Initialization of this Action failed:" + ex.getmessage (), ex);
  21. }
  22. }
  23. protected void Initaction () throws Exception {
  24. }
  25. protected Event Success () {
  26. return Geteventfactorysupport (). Success (this);
  27. }
  28. protected Event Success (Object result) {
  29. return Geteventfactorysupport (). Success (this, result);
  30. }
  31. protected Event Error () {
  32. return Geteventfactorysupport (). Error (this);
  33. }
  34. protected Event Error (Exception e) {
  35. return Geteventfactorysupport (). Error (this, e);
  36. }
  37. protected Event Yes () {
  38. return Geteventfactorysupport (). Yes (this);
  39. }
  40. protected Event No () {
  41. return Geteventfactorysupport (). No (this);
  42. }
  43. protected Event Result (boolean booleanresult) {
  44. return Geteventfactorysupport (). Event (this, booleanresult);
  45. }
  46. protected Event result (String eventId) {
  47. return Geteventfactorysupport (). Event (this, eventId);
  48. }
  49. protected Event result (String eventId, AttributeMap resultattributes) {
  50. return Geteventfactorysupport (). Event (This, eventId, resultattributes);
  51. }
  52. protected Event Result (string eventId, String resultattributename, Object resultattributevalue) {
  53. return Geteventfactorysupport (). Event (This, EventId, Resultattributename, Resultattributevalue);
  54. }
  55. public Final Event execute (requestcontext context) throws Exception {
  56. Event result = Dopreexecute (context);
  57. if (result = = null) {
  58. result = Doexecute (context);
  59. Dopostexecute (context);
  60. } Else {
  61. if (logger.isinfoenabled ()) {
  62. Logger.info ("Action execution disallowed;  Pre-execution result is ' "+ result.getid () + " ' ");
  63. }
  64. }
  65. return result;
  66. }
  67. protected String getactionnameforlogging () {
  68. return Classutils.getshortname (GetClass ());
  69. }
  70. protected Event Dopreexecute (RequestContext context) throws Exception {
  71. return null;
  72. }
  73. //Abstract method
  74. protected Abstract Event Doexecute (RequestContext context) throws Exception;
  75. protected void Dopostexecute (RequestContext context) throws Exception {
  76. }
  77. }

In abstract class AbstractAction, there are methods of concrete implementation, and there is no concrete implementation of abstract methods

[Java]View Plaincopy
    1. Abstract methods
    2. Protected abstract Event Doexecute (RequestContext context) throws Exception;

It is important to note that in an abstract class, if the method does not have a concrete implementation (that is, there is no {}after the method), you must add an abstract to declare the method, and the interface does not need to use abstract to declare (the abstract class is called an abstract class, It is because it contains an abstract method. Classes that contain abstract methods are called abstract classes.

--------------------------------------------------------------------------------------------------------------- ---------------------------------

Class that contains the abstract modifier is an abstract class, and the abstract class cannot create an instance object, and the classes containing the abstract method must be defined as abstract class, and the method in the abstract class does not have to be abstract. Abstract to define abstract methods must be implemented in a specific subclass, so ah, there can be no abstract constructor method or abstract static method, if the subclass does not implement all the methods in the abstract parent class, then the subclass must also be defined as an abstract class.

Interface (interface) can be said to be a special case of abstract classes. All methods in an interface must be abstract, and the method definition in the interface defaults to public abstract. The variables in the interface are global constants, which are public static final adornments.

Look at their grammatical differences!

1, the abstract class can have a construction method, and the interface cannot have a construction method.

2, abstract classes can have ordinary member variables, and interfaces cannot have ordinary member variables.

3, abstract classes can contain non-abstract ordinary methods, and all the methods in the interface must be abstract, not a non-abstract ordinary method.

4, the access type of an abstract method in an abstract class can be public, protected, and the default type, but the abstract method in the interface is only public type, and the default is the public abstract type.

5, a static method can be included in an abstract class, and a static method cannot be contained within an interface.

6, the abstract class and interface can contain static member variables, the access type of static member variables in the abstract class can be arbitrary, but the variables defined in the interface can only be public static type, and the default is the public static type.

7, a class can implement multiple interfaces, but can inherit only one abstract class.

Add the difference between the two in the application:

Interface is more in the system framework design method to play a role in the main definition of communication between modules, and abstract classes in the implementation of code to play a role, you can implement code reuse

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.

Tags Index: