Abstract class and interface connection and Difference

Source: Internet
Author: User
Tags define abstract
Keywords: differences between abstract classes and interfaces

Abstract class and interface are two mechanisms supported for the definition of abstract classes in Java. It is precisely because of the existence of these two mechanisms that give Java powerful object-oriented capabilities. Abstract class and interface have great similarity in support for the definition of abstract classes, and can even be replaced with each other, therefore, when defining abstract classes, many developers may choose abstract classes and interfaces at will.

In fact, there is a big difference between the two. Their choices even reflect the understanding of the nature of the problem domain, and whether the understanding of the design intent is correct and reasonable. This article will analyze the differences between them and try to provide developers with a basis for selection between them.

I. understanding abstract classes

Abstract class and interface are used for abstract classes in Java language (abstract classes in this article are not translated from abstract class, it represents an abstract body, abstract class is a method used to define abstract classes in the Java language. Please note that it is defined). So what is an abstract class and what benefits can it bring to us by using abstract classes?

In the concept of object-oriented, we know that all objects are depicted through classes, but this is not the case. Not all classes are used to depict objects. If a class does not contain enough information to depict a specific object, such classes are abstract classes. Abstract classes are often used to represent the abstract concepts we have come up with in the analysis and design of problem domains. They are an abstraction of a series of seemingly different but essentially identical specific concepts.

For example, if we develop a graphic editing software, we will find that some specific concepts such as circles and triangles exist in the problematic domain. They are different, however, they all belong to the concept of shape. The concept of shape does not exist in the field of problem. It is an abstract concept. Abstract concepts cannot be instantiated because they do not have specific concepts in the problem field.

In the Object-Oriented field, abstract classes are mainly used to hide types. We can construct a fixed abstract description of a group of rows, but this behavior can have any specific implementation method. This abstract description is an abstract class, and any possible implementations of this group are represented as all possible Derived classes. The module can operate on an abstract body. Because the module depends on a fixed abstract body, it may not be allowed to be modified. At the same time, the behavior function of this module can be extended by deriving from this abstract body. Those familiar with OCP must know that abstract classes are the key to implementing an OCP (open-closed principle), the core principle of object-oriented design.

Ii. View abstract class and interface in terms of syntax definition

At the syntax level, the Java language provides different definitions for abstract class and interface. The following describes how to define an abstract class named demo. You can use abstract class to define a demo abstract class as follows:

 

Java Code
    1. Abstract class demo {
    2. Abstract void Method1 ();
    3. Abstract void method2 ();
    4. ...
    5. }

 

 

The following method is used to define the demo abstract class using the interface:

 

Java code
    1. Interface demo {
    2. Void Method1 ();
    3. Void method2 ();
    4. ...
    5. }

 

 

In the abstract class method, the demo can have its own data members or non-Abstarct member methods. In the implementation of the interface method, demo can only have static data members that cannot be modified (that is, they must be static final, but generally do not define data members in the interface). All member methods are abstract. In a sense, interface is a special form of abstract class.

From the programming point of view, abstract class and interface can be used to implement the idea of "Design by contract. However, there are some differences in usage.

Abstract class represents an inheritance relationship in Java. A class can only use an inheritance relationship once. However, a class can implement multiple interfaces. Maybe this is a compromise between Java designers and Java's support for multi-inheritance.

Secondly, in the definition of abstract class, we can assign the default behavior of the method. However, in the interface definition, a method cannot have default behavior. to bypass this restriction, you must use a delegate. However, this increases complexity and sometimes causes great trouble.

Another serious problem still exists when the default behavior cannot be defined in the abstract class, which may cause maintenance trouble. Because if you want to modify the interface of the class (usually expressed by abstract class or interface) to adapt to the new situation (for example, adding a new method or adding a new parameter to the used method) it will be very troublesome, and it may take a lot of time (especially when there are many derived classes ). However, if the interface is implemented through abstract class, you may only need to modify the default behavior defined in abstract class.

Similarly, if the default behavior cannot be defined in the abstract class, the same method will appear in every derived class of the abstract class, in violation of the "one rule, one place" principle, code duplication is also not conducive to future maintenance. Therefore, be careful when selecting abstract class and interface.

Iii. abstract class and Interface

The difference between abstract class and interface is discussed from the perspective of syntax definition and programming. The difference between these layers is relatively low-level and non-essential. This article will analyze the differences between abstract class and interface on another level. The author believes that only by analyzing at this level can we understand the essence of the two concepts.

As mentioned above, Abstarct class represents an inheritance relationship in Java. To make the inheritance relationship reasonable, there must be a "is a" relationship between the parent class and the derived class, that is, the concept of the parent class and the derived class should be essentially the same. For an interface, it is not required that the implementer of the interface and the interface definition are essentially consistent in concept, but only implement the contract defined by the interface. In order to make the discussion easier to understand, we will explain it through a simple example below.

Consider this example. Suppose there is an abstract concept about the door in our problem field. The door has two actions: open and close, in this case, abstract class or interface can be used to define a type that represents the abstract concept. The definitions are as follows:

 

Use abstract class to define door:

 

Java code

 

    1. Abstract class door {
    2. Abstract void open ();
    3. Abstract void close ();
    4. }

Use the interface method to define the door:

 

Java code
    1. Interface door {
    2. Void open ();
    3. Void close ();
    4. }

 

 

For other specific door types, extends can use the door defined in abstract class or implements to use the door defined in interface mode. It seems that there is no big difference between abstract class and interface.

If you want the door to have the alarm function. How can we design the class structure for this example (in this example, we mainly want to demonstrate the differences between abstract class and interface in the design concept, other irrelevant issues are simplified or ignored.) The following describes possible solutions and analyzes these different solutions at the design concept layer.

Solution 1:

Add an alarm method to the door definition as follows:

 

Java code

 

 

Or

 

Java code
    1. Interface door {
    2. Void open ();
    3. Void close ();
    4. Void alarm ();
    5. }

 

 

The alarmdoor with alarm function is defined as follows:

 

Java code
    1. Class alarmdoor extends door {
    2. Void open (){... }
    3. Void close (){... }
    4. Void alarm (){... }
    5. }

 

 

Or

 

Java code
    1. Class alarmdoor implements door {
    2. Void open (){... }
    3. Void close (){... }
    4. Void alarm (){... }
    5. }

 

 

This method violates a core principle in object-oriented design, ISP (interface segregation priciple ), in the definition of door, the inherent behavior methods of the door concept are mixed with the behavior methods of another concept "alarm. One problem is that the modules that rely solely on the door concept will change due to changes in the concept of "alarm" (for example, modifying the parameters of the alarm method.

Solution 2:

Since open, close, and alarm belong to two different concepts, they should be defined in abstract classes that represent these two concepts according to the ISP principle. The two concepts are defined by abstract class. Both concepts are defined by interface. One is defined by abstract class, and the other is defined by interface.

Obviously, because the Java language does not support multiple inheritance, both concepts are defined using abstract class. The latter two methods are feasible, but their selection reflects the understanding of the concept nature in the problem field, and whether the reflection of the design intent is correct and reasonable. Let's analyze and explain them one by one.

If both concepts are defined using the interface method, two problems are identified:

1. We may not understand the problem. Is alarmdoor actually a door or an alarm?

2. If we have no problem in understanding the problem field, for example, we have found that alarmdoor is essentially consistent with door through analysis of the problem field, therefore, our design intent cannot be correctly revealed during implementation, because the definitions of these two concepts (both using the interface method definition) do not reflect the above meaning.

If our understanding of the problem field is: alarmdoor is essentially a door, it has the alarm function at the same time. How can we design and implement it to clearly reflect what we mean? As mentioned above, abstract class represents an inheritance relation in Java, and the inheritance relation is essentially a "is a" relation. So we should use the Abstarct class method to define the concept of door. In addition, alarmdoor has the alarm function, indicating that it can complete the behaviors defined in the alarm concept. Therefore, the alarm concept can be defined through the interface method. As follows:

 

Java code
    1. Abstract class door {
    2. Abstract void open ();
    3. Abstract void close ();
    4. }

 

Java code
    1. Interface alarm {
    2. Void alarm ();
    3. }

 

Java code
    1. Class alarmdoor extends door implements alarm {
    2. Void open (){... }
    3. Void close (){... }
    4. Void alarm (){... }
    5. }

 

 

This implementation method can clearly reflect our understanding of the problem field and correctly reveal our design intent. Abstract class represents the "is a" relation, and interface represents the "like a" relation. You can use it as a basis for your selection, of course, this is based on the understanding of the problem field. For example, if we think that alarmdoor is essentially an alarm and has the door function, then the above definition method will be reversed.

Abstract class and interface are two methods of defining abstract classes in Java. They have great similarity. However, their choices often reflect the understanding of the essence of concepts in the problem field, and whether the reflection of design intent is correct and reasonable, because they represent different relationships between concepts (although they all implement the required functions ). This is also a common use of language.

To sum up a few words:

1. abstract classes and interfaces cannot be directly instantiated. to instantiate them, the abstract class variables must point to subclass objects that implement all abstract methods, and the interface variables must point to class objects that implement all interface methods.

2. abstract classes must be inherited by quilt classes, and interfaces must be implemented by classes.

3. The interface can only be used for method declaration. The abstract class can be used for method declaration or method implementation.

4. the variables defined in the interface can only be public static constants. the variables in the abstract class are common variables.

5. the abstract methods in the abstract class must be implemented by all the quilt classes. If the subclass cannot all implement the parent class abstract methods, the subclass can only be an abstract class. Similarly, if an interface cannot be fully implemented, the class can only be an abstract class.

6. abstract methods can only be declared and cannot be implemented. Abstract void ABC (); cannot be written as abstract void ABC (){}.

7. There can be no abstract methods in the abstract class.

8. If an abstract method exists in a class, the class can only be an abstract class.

9. abstract methods must be implemented, so they cannot be static or private.

10. An interface can inherit an interface and inherit multiple interfaces, but a class can only inherit one interface.

Abstract classes have their advantages, especially for public implementation code. Abstract classes can ensure implementation hierarchies and avoid code duplication. However, even when using image extraction classes, do not ignore the principle of defining behavior models through interfaces. From a practical point of view, if you rely on abstract classes to define behavior, it often leads to overly complex inheritance relationships, and defining behavior through interfaces can effectively separate behavior and implementation, it facilitates code maintenance and modification.

 

 

 

This article Reprinted from http://fzfx88.javaeye.com/blog/115393

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.