Explanations of abstract class and interface in Java and their similarities and differences

Source: Internet
Author: User

Tags: abstract NTS GRE reference end cannot condition triangle STR

(i) overview
In the Java language, abstract classes and interface are the two mechanisms that support the definition of an abstraction class. It is precisely because of the existence of these two mechanisms

In order to give Java a powerful object-oriented capability. The abstract class and interface have a

Large similarities, and can even be replaced, so many developers are doing abstract class definitions for the interface

Choice seems more casual. In fact, there is a big difference between the two, for their choice even reflects the nature of the problem areas of the rationale

The understanding of the design intent is correct and reasonable.

Abstract class and interface are used in the Java language for abstraction classes (abstract classes in this article are not from an abstract class

Translated, it represents an abstraction, and the abstract class is a method for defining abstract classes in the Java language, so readers should note

Definition, what are the benefits of using abstract classes and what are abstract classes?


In object-oriented concepts, we know that all objects are depicted through classes, but not in the opposite way. Not all

Classes are used to depict objects (materialization of classes), if a class does not contain enough information to depict a specific object, such

Classes are abstract classes. Abstract classes are often used to characterize the abstract concepts we derive in the analysis and design of problem areas, and are a series of seemingly

Different, but essentially identical, abstractions of specific concepts. For example: if we develop a graphical editing software, we will find the problem areas

There are some specific concepts of circle and triangle, they are different, but they all belong to the concept of shape, the concept of shape

Problem areas do not exist, it is an abstract concept. It is precisely because the concept of abstraction does not correspond to specific concepts in the problem domain, so it is used to

Abstract classes that characterize abstract concepts cannot be instantiated.


Abstract classes are primarily used for type concealment in the object-oriented realm. We can construct an abstract description of a fixed set of behaviors, but

It is this group of behaviors that can be implemented in any specific way possible. This abstract description is an abstract class, and this set of arbitrary possible concrete implementations

is represented by all possible derived classes. Like, an animal is an abstract class, Human, Monkey, Tiger is a concrete implementation of derived classes, we can

Use animal types to hide the types of people, monkeys, and tigers.

(ii) analysis from a grammatical definition

At the syntactic level, the Java language gives different definitions for abstract class and interface, and the following is an example of defining an abstract class called Demo to illustrate this difference.

The way to define the demo abstract class using the abstract class is as follows:

Abstract class demo{
abstract void method1 ();
abstract void method2 ();
...

The way to define the demo abstract class using interface is as follows:

Interface demo{
void Method1 ();
void Method2 ();
...
}

In the abstract class mode, the demo can have its own data members, but also can have non-abstract member methods, and in the implementation of the interface mode, the demo can only have

Static data members that cannot be modified (that is, must be static final, but data members are not generally defined in interface), all member methods are abstract

。 In a sense, interface is a special form of abstract class.

From a programmatic point of view, both the abstract class and the interface can be used to implement the idea of "design by contract". But there are some differences in the use of specific
Of


First, the abstract class represents an inheritance relationship in the Java language, and a class can only use one inheritance relationship (because Java does not support multiple inheritance----). But

A class can implement multiple interface. Perhaps this is a compromise of the Java language designer in considering Java's support for multiple inheritance.

Second, in the definition of abstract class, we can give the method the default behavior. But in the definition of interface, the method does not have the default behavior, in order to circumvent this

Restrictions, you must use a delegate, but this adds some complexity and can sometimes cause a lot of trouble.

There is another serious problem with the inability to define default behavior in an abstract class, which can cause maintenance headaches. Because if you later want to modify the interface of the class (General pass

The abstract class or interface to accommodate new situations (for example, adding new methods or adding new parameters to a used method) can be very troublesome

, it may take a lot of time (especially for many of the derived classes). But if the interface is implemented by an abstract class, then it is possible to modify the definition only

The default behavior in the abstract class is yes.

Similarly, if the default behavior cannot be defined in an abstract class, it causes the same method implementation to appear in each derived class of the abstract class, violating the "one Rule,one Place"

Principle, resulting in code duplication, is also detrimental to future maintenance. Therefore, you should be very careful when choosing between the abstract class and the interface.


(iii) analysis from the design concept level

It mainly discusses the difference between abstract class and interface from the angle of grammar definition and programming, and the difference between these layers is comparatively low-level and non-essential. This section will be from another

Level: abstract class and interface reflect the design concept, to analyze the difference between the two. The author believes that the analysis from this level can understand the essence of both concepts

Area

As mentioned earlier, abstract class embodies an inheritance relationship in the Java language, in order to make the inheritance relationship reasonable, there must be a "is-a" relationship between the parent class and the derived class.

That is, the parent class and the derived class should be the same in nature. For interface, it does not require interface and interface definitions to be consistent in concept.

, it is just a contract that implements the interface definition. To make the discussion easy to understand, a simple example is described below.

Consider an example of the assumption that in our problem domain there is an abstraction about door, the door has the ability to execute two actions open and close, at which point we can

Abstract class or interface defines a type that represents the abstract concept, as shown in the following ways:

Define door using the abstract class method:


Abstract class door{
abstract void open ();
abstract void close ();
}

Define door using the interface method:

Interface door{
void Open ();
void Close ();
}

Other specific door types can be extends using the door defined by the abstract class or implements interface defined using door mode. It looks as if using

There is no big difference between abstract class and interface.

If you now require door also have the function of alarm. How do we design the class structure for this example (in this case, mainly to show the abstract class and

interface reflected in the design concept of the difference, other aspects of irrelevant issues have been simplified or ignored)? Here's a list of possible solutions, and from the design concept layer to face these

Different scenarios for analysis.

Solution One:

Simply add a alarm method to the definition of door, as follows:

Abstract class door{
abstract void open ();
abstract void close ();
abstract void alarm ();
}

Or

Interface door{
void Open ();
void Close ();
void Alarm ();
}

Then 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 approach violates a core principle in object-oriented design. ISP (Interface segregation Principle), in the definition of door, the behavior inherent in the door concept itself

Method and another concept of "alarm" behavior method mixed together. One of the problems that this raises is that modules that rely solely on the concept of door will be due to the concept of "alarm"

Change (for example: Modifying the parameters of the alarm method) and vice versa.

Solution Two:

Since open, close and alarm belong to two different concepts, they should be defined separately in an abstract class that represents both concepts, according to the ISP principle. There are two ways to define this:

Both concepts are defined using the abstract class method, the concept is defined using the abstract class method, and the other concept uses the interface method.

interface method definition.


Obviously, because the Java language does not support multiple inheritance, it is not feasible for both concepts to be defined using the abstract class method. The last two ways are possible, but for it

The choice reflects the understanding of the nature of the concept in the problem domain and the correctness and reasonableness of the design intent. We hit analysis, explain.

If both concepts are defined using the interface approach, then two questions are reflected: 1. We may not understand the problem areas clearly, alarmdoor the concept in the end

Is it a door or an alarm? 2. If our understanding of the problem area is not a problem, for example: we find Alarmdoor in the conceptual nature and door is a

, we have not been able to properly disclose our design intent when we implement it, because the definitions of both concepts (which are defined using the interface method) do not reflect the

Yi.

If our understanding of the problem area is: Alarmdoor is inherently door in concept, and it has a function of alerting. How do we design and implement to clearly reflect

What do we mean by that? As already mentioned, abstract class represents an inheritance relationship in the Java language, whereas an inheritance relationship is essentially a "is-a" relationship. So for the concept of door

, we should use the ABSTARCT class method to define. In addition, Alarmdoor also has the alarm function, indicating that it can complete the alarm concept defined behavior, so the alarm concept can be

Defined by the interface method. As shown below:

Abstract class door{
abstract void open ();
abstract void close ();
}
Interface alarm{
void Alarm ();
}
Class Alarm Door extends Door implements alarm{
void Open () {...}
void Close () {...}
void alarm () {...}
}

This kind of realization basically can clearly reflect our understanding of the problem area, and reveal our design intention correctly. In fact, abstract class represents the "is-a" relationship

, interface represents the "like-a" relationship, which can be used as a basis for selection, of course, based on an understanding of the problem area, such as: if we think

Alarmdoor in the concept of nature is the alarm, but also has the function of door, then the definition of the above way will be reversed.

(iv) Abstract class summary

The 1.abstract class usually contains one or more abstract methods, and the abstract method does not provide the implementation; The class containing the abstract method must be declared abstract class;abstract

All specific subclasses of class must provide a specific implementation for the superclass, and if the subclass does not implement an abstract method of the superclass, it will produce a compilation error unless the subclass is also declared abstract.

The 2.abstract class declares the common properties and behavior of classes in a class hierarchy, and because constructors cannot be inherited, constructors cannot be declared as abstract methods;

Instantiate an object of an abstract class, but be able to declare a variable of an abstract type that can be used to refer to an object of a subclass

(v) Interface Summary

1. The interface starts with interface and contains a set of abstract methods that are implicitly considered public, which can contain variables, default to static final, and must give their initial value, so the actual

The present class cannot be redefined, nor can it change its value; The implementation interface must implement all of these methods, there is no implementation method in the interface, and all the member methods are abstract.


2. If a class does not implement any interface methods, it is an abstract class, and the class must be declared with the keyword abstract; Implementing an interface is like reaching a protocol with the compiler.

"I will declare all the methods that the interface has developed."


(vi) Summary


1.abstract class represents an inheritance relationship in the Java language, and a class can only use one inheritance relationship at a time. However, a class can implement multiple interface.

2. You can have your own data members in the abstract class, or you can have non-ABSTARCT member methods, and in interface, only static data that cannot be modified

Members (that is, must be static final, but generally do not define data members in interface), all member methods are abstract.

The 3.abstract class and interface reflect a different design concept. In fact, abstract class represents the "is-a" relationship,

Interface represents a "like-a" relationship.

 


4. Interfaces are generally used to replace the class in an abstract class when there is no default implementation available for inheritance (that is, there are no instance variables and default method implementations).

The 5.abstract class is another form of contract that is designed to meet the requirements of the implementation, and the interface is the server's requirement for the client.

The 6.abstract class is a base class that cannot be instantiated, and an interface is a declaration that implements the method for each class that corresponds to the interface.


7. A subclass if you implements an interface, you must implement all the methods in the interface (whether or not it is required); If you inherit an abstract class, you only need to implement the required method

, which is an advantage of abstract classes

8. If the method name defined in one of the interfaces changes, then all subclasses that implement this interface will obviously fail to compile because the method name they implement is no longer present, which is

A disadvantage of the interface, and if a non-abstract method is changed in the abstract class, there is no problem, just a new method is added for the subclass.


9. Looking at the previous two points, it seems that abstract classes have more advantages than interfaces, but it has an irreparable disadvantage: a subclass can have only one parent class. A extends B.

So that a has all the methods and functions of B, but when a also wants to have C function. Can not be achieved through A extends C, and need to take some detours. Current system architecture

The trend is made by targeting abstractions (excuses, abstract classes) rather than specific programming, and subdividing the functionality as much as possible. This needs to be achieved by implementing multiple interfaces, and it is clear that pumping

The image class cannot provide such functionality. From the point of view of system reconfiguration, it is very convenient for a concrete class to abstract out the interface. Just write an interface that defines all the methods of a specific class,

Then implement this interface for this specific class. Abstract classes are more complex, such as B extends A, C extends B if you want to abstract an abstract for C

Class D, you need to find its top-level A to start from scratch, because you can't do C extends D

Explanations of abstract class and interface in Java and their similarities and differences (RPM)

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: