Comparison of Java Abstract classes and interfaces

Source: Internet
Author: User
Tags define abstract

The following article is very thorough, so it is reproduced and corrected.

Abstract class and interface are two types of mechanisms that support the definition of abstract classes in Java, it gives Java powerful object-oriented capabilities. Abstract classes and interfaces have great similarity in support for abstract class definitions, and can even be replaced with each other. Therefore, many developers may choose abstract classes and interfaces when defining abstract classes. 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 classes and interfaces are used for abstract classes in Java. (abstract classes in this document are not translated from abstract classes. They represent 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 abstractions 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 actions, but this group of actions 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. Readers familiar with OCP must know that, in order to realize a core principle of object-oriented design, OCP (open-closed)
Abstract class is the key.

Ii. View abstract classes and interfaces at the syntax definition level

At the syntax level, Java provides different definitions for abstract classes and interfaces. The following describes how to define an abstract class named demo.

The following describes how to use an abstract class to define a demo abstract class:
Abstract class demo {
Abstract void Method1 ();
Abstract void method2 ();
...
}

The following method is used to define the demo abstract class using the interface:
Interface demo {
Void Method1 ();
Void method2 ();
...
}

In the abstract class mode, the demo can have its own data members or non-Abstarct member methods. In the implementation of the interface mode, 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, an interface is a special form of abstract class.

Iii. abstract classes and interfaces from the programming perspective

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

1. First, an 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.

2. In the definition of an abstract class, we can assign the default behavior of the method. However, in the interface definition, methods cannot have default behaviors. to bypass this restriction, you must use delegation. However, this increases complexity and sometimes causes great trouble.

Define the default behavior in the abstract class. Once the behavior method in the abstract class changes, it will affect its subclass. But on the other hand, if the default behavior is not defined in the abstract class, the same method will appear in every derived class of the abstract class, violating the "one rule, one place" principle, code duplication is also not conducive to future maintenance.

Therefore, be careful when selecting abstract classes and interfaces.

Iv. View abstract classes and interfaces from the design concept level

The above mainly discusses the differences between abstract classes and interfaces from the perspective of syntax definition and programming. The differences between these levels are relatively low-level and non-essential. This section analyzes the differences between abstract classes and interfaces 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, abstract classes reflect 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 to say, the concept of the parent class and the derived class should be essentially the same (for more information about the "is a" relationship in the references [3], for interested readers, refer ). Otherwise, the implementer of the interface is not required to be consistent with the interface definition in concept. It only implements the contract of the interface definition. 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, we can use an abstract class or interface to define a type that represents the abstract concept. The definition methods are as follows:
Use an abstract class to define the door:
Abstract class door {
Abstract void open ();
Abstract void close ();
}
 
Use the interface to define the door:
Interface door {
Void open ();
Void close ();
}

For other specific door types, you can use an abstract class to define the door or implements using the interface to define the door. It seems that there is no big difference between using abstract classes and interfaces.
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 classes and interfaces in the design concept, other irrelevant issues have been simplified or ignored )? Below we will list possible solutions and analyze these different solutions from the design concept layer.

Solution 1:
Add an alarm method to the door definition as follows:
Abstract class door {
Abstract void open ();
Abstract void close ();
Abstract void alarm ();
}
Or
Interface door {
Void open ();
Void close ();
Void alarm ();
}
The alarmdoor with alarm function is defined as follows:
Class alarmdoor extends door {
Void open (){... }
Void close (){... }
Void alarm (){... }
}
Or
Class alarmdoor implements door {
Void open (){... }
Void close (){... }
Void alarm (){... }
}

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 using abstract classes. Both concepts are defined using interfaces. One is defined using abstract classes, and the other is defined using interfaces.
Obviously, because the Java language does not support multiple inheritance, it is not feasible to define both concepts using abstract classes. 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, there are two problems: 1. We may not understand the problem field clearly. Is the concept of 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 interface-based definitions) do not reflect the above meaning.
If our understanding of the problem field is: alarmdoor is essentially a door in concept, it also has the alarm function. How can we design and implement it to clearly reflect what we mean? As mentioned above, abstract classes represent an inheritance relationship in Java, and the inheritance relationship is essentially a "is a" relationship. Therefore, we should use abstract classes 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 interfaces. As follows:

Abstract class door {
Abstract void open ();
Abstract void close ();
}
Interface alarm {
Void alarm ();
}
Class alarmdoor extends door implements alarm {
Void open (){... }
Void close (){... }
Void alarm (){... }
}

This implementation method can clearly reflect our understanding of the problem field and correctly reveal our design intent. In fact, the abstract class represents the "is a" link, and the interface represents the "like a" link. 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.

V. Summary

Summarize the differences between abstract classes and Java interfaces.Abstract classes without non-abstract methods are very similar to interfaces, but pay attention to the following points:

1,A class can implement any number of interfaces, but it can only expand one abstract class at most;

2,Abstract classes allow several non-abstract methods, and all methods in interfaces must be abstract, whether or not their methods are explicitly declared as abstract;

3,Abstract classes can declare and use fields, but interfaces cannot, although interfaces can create static final constants;

4,The visible modifier of an abstract class method can be public, protected, private, or non-modifier (indicating intra-package visibility). The method visibility modifier of an interface can only be public;

5,Abstract classes can define constructors, but interfaces cannot;

Abstract classes and interfaces are two methods of defining abstract classes in Java. They have great similarities. However, their choices often reflect the understanding of the concept nature in the problem field, and whether the reflection of the design intent is correct and reasonable, because they represent different relationships between concepts (although they all implement the required functions ). Therefore, which one to use depends on the system's planning and needs. The interfaces are neat and clear, and the standards are clear. Abstract classes can be used to handle common things. It is usually used to use two classes together. First, an interface is created for some mechanisms, and then an abstract class is designed to implement this interface. Some methods are implemented as default actions, so that non-modifiable sub-classes can be reused.

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.