Abstract classes and interfaces in Java

Source: Internet
Author: User
Tags define abstract

I haven't seen such an incisive article for a long time! The author wrote it too well! If you are learning Java or want to know about abstract classes and interfaces, do not miss it! I strongly recommend it!

  1. Differences between interfaces and abstract classes in OOP
  2. Java interface and the nature of Inheritance
  3. Deep understanding of interfaces and abstract classes
     

Differences between interfaces and abstract classes in OOP

Interfaces and abstract class in OOP are two different concepts.

When we use them, we often use them together without any difference. You may have some opinions on their differences in definition.

Here I don't need any technical terms or anything. The word "annoying" will be discussed in the simplest vernacular.

In fact, these two things are very widely used. I have been depressed for a long time to understand.

When we abstract an object, we classify it and divide its attributes and main methods into a class. At this time, we use abstract class, the interface is used to add functions for external use.

In general applications, the interface is directly external, and the abstract class is followed by the class of the specific implementation method.

Here is a simple example:

Now we want to analyze the "computer" entity

First, the computer components include (host, display) us, and then analyzes the behavior of the components. The host can (START, shut down), or the monitor can (Open, close ), these are basic and necessary functions of computers.

Abstract class jisuanji {

String Zhuji, xianshiqi;

Abstract zj_on ();

Abstract zj_off ();

Abstract xsq_on ();

Abstract xsq_off ();

}

The above is the basic composition of the computer, but our computer not only has these devices, we also need the keyboard, mouse or something, these are all necessary, otherwise, the computer won't be able to complete his basic task. We can use inheritance to implement it.

Abstract class PC extends jisuanji {

String shubiao, jianpan;

Abstract sb_click ();

Abstract sb_dblclack ();

}

We have basically completed the complete computer components, but our PC is a multi-functional device. Not everyone uses it for basic computing. We can use it to watch movies, listen to music, or something, in this case, we need to expand its functions. These devices are not necessarily needed on the computer. The interface is used here.

Our computer now only needs basic functions and the function of playing music. We use interfaces to implement it.

Interface music {

Public void play ();

}

Here, the function of playing music is generated.

Integrate these functions

Class computer extends PC implements music {

<Implementation>

}

Here we have made a computer with music functions, and we may need other functions. At this time, we can make full use of the advantages of interfaces to add these functions at will.

After the specific example is completed, let's look back at the difference between interfaces and abstract classes. abstract classes encapsulate the main functions when using them, the addition of main components (such as the upgrading of computers) is implemented through abstract classes, while the interface is biased towards the addition, deletion, and management of additional functions.

At this time, someone may ask, why is it so complicated to define an abstract class and define an interface? It is convenient and understandable to write these functions in a class. This kind of idea is handy, understandable, and easy to write when solving small problems.

However, using this method to solve complex problems exposes many drawbacks:

When solving a complex problem, we need to first classify it, then refine the classification, and first consider the order of solving the problem, finally, we will compile the process after we have mastered every module of the problem. In this way, we will be very comfortable in the face of a complicated problem, and the way we write them together cannot take the problem into consideration, even if we barely think about it, it is estimated that few people can understand the code, and it is very cumbersome to use and cannot find a clue.

Things are not static. They are constantly evolving and may be subject to many changes. We often need to expand and delete functions of an existing program, the method we analyzed here can be used to solve this problem in a very systematic manner (to implement the addition of main functions using class inheritance, and to add auxiliary functions using interfaces for management and classification, this is well-organized). You do not have to change the code a lot when solving complex problems or making many changes.

The idea of OOP helps us solve a lot of complicated problems. Here we will not list them one by one, but here we will focus on them.

Java interface and the nature of Inheritance

Most people think that the meaning of an interface is to replace multiple inheritance. As we all know, Java does not have the multi-Inheritance Mechanism like C ++, but it can implement multiple interfaces. In fact, this is very far-fetched. interfaces and inheritance are completely different. Interfaces do not have the ability to replace multiple inheritance, and they do not have this obligation. The function of an interface, in a word, is the type of class ). You can better manage different types of classes by assigning them to different interfaces. The essence of OO, I think, is the abstraction of objects, the interface that best reflects this point is. Why do we discuss that the design patterns are only for languages with abstract capabilities (such as C ++, Java, and C #) because the design patterns are studied, it is actually how to reasonably abstract. (Cowboy's famous saying is that "abstraction is the part of image extraction". It seems ridiculous, but it is actually the most reasonable ).
The most basic design pattern is the factory pattern. In a very simple application recently, I want to try to port my program among multiple databases. Of course, this involves many problems. It is a headache to be compatible with the SQL statements of different DBMS. We may want to simplify the problem and only consider how to connect to different databases.

Suppose I have many classes, namely MySQL. java, sqlserver. java, Oracle. java and db2.java connect to different databases, and return a connection object in a unified manner. They all have a close method to close the connection. You only need to select different classes for your DBMS. But what database does my user use? I don't know. I want to modify the code as little as possible to meet his needs. I can abstract the following interfaces:

Package org. bromon. test;
Public interface DB
{
Java. SQL. Connection opendb (string URL, string user, string password );
Void close ();
}

This interface only defines two methods without any actual code. The specific code is provided by the class implementing this interface, such as MySQL. Java:

Package org. bromon. test;
Import java. SQL .*;
Public class MySQL implements DB
{
Private string url = "JDBC: mysql: localhost: 3306/test ";
Private string user = "root ";
Private string Password = "";
Private connection conn;
Public connection opendb (URL, user, password)
{
// Database connection code
}

Public void close ()
{
// Close the database
}
}

Similar to Oracle. Java, and so on, the interface dB gives these classes a class. In the application, we define the object as follows:

Org. bromon. Test. DB mydb;
When using mydb to operate databases, you don't have to worry about which class I actually use. This is the so-called "Open-Close" principle. However, the problem is that the interface cannot be instantiated. mydb = new dB (). Such code is absolutely incorrect. We can only use mydb = new MySQL () or mydb = new Oracle (). The problem is that I still need to specify the class to be instantiated, and the interface is useless. So we need a factory:
Package org. bromon. test;
Public class dbfactory
{
Public static dB connection getconn ()
{
Return (New MySQL ());
}
}

So the instantiated code becomes: mydb = dbfactory. getconn ();

This is the most basic factory in the 23 modes. The factory class is responsible for instantiating which class, and other program logic is to operate on the DB interface, this is "programming for interfaces ". Responsibility has been shirked to the factory class. Of course, you can continue to define the factory interface and continue to throw the responsibility, which will evolve into abstract factory ).

During the whole process, the interface is not responsible for any specific operations. If other programs want to connect to the database, they only need to construct a DB object and then OK, regardless of how the factory class changes. This is the meaning of the interface ---- abstraction.

It is easy to understand the concept of inheritance. Why inherit? Because you want to reuse the code? This is definitely not a reason. The significance of inheritance also lies in abstraction, rather than code reuse. If object A has a run () method, object B also wants to use this method, so someone will use Class B extends. This is a brainless approach. If we instantiate a A in B and call the run () method of A, can we achieve the same purpose? As follows:

Class B
{
A A = new ();
A. Run ();
}

This refers to the reuse of Code by means of class aggregation, the prototype of the delegation mode, and the practice consistently advocated by gof.

So what is the significance of inheritance? In fact, this is caused by historical reasons. In the beginning, the OO language only had inheritance and no interfaces, so it was only allowed to implement abstraction by inheritance. Please note that the inheritance was originally intended to be abstract, rather than code reuse (although inheritance also plays this role), this is one of the most serious errors of many bad Java books. The shadows they have caused have not been completely removed yet, bad books are harmful, especially entry-level books. The traffic is too high. When should I use inheritance? It is used only in abstract classes, and should not be used in other cases. Abstract classes cannot be instantiated. They only provide a template, which can be used to illustrate the problem.

The source of all evil in software development is repeated code rather than code reuse. Second, bad inheritance, especially for C ++ programmers. It is wise to ban multi-inheritance in Java to stop the use of inheritance, but many people do not understand it. Java can better reflect the design, which is one of the reasons why I am fascinated.

Deep understanding of interfaces and abstract classes

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.

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 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 abstract classes are the key to implementing an open-closed principle Principle of object-oriented design.

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:

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 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.

Abstract class and interface are not the focus of this Article for more details on syntax definition. Readers can refer to references [1] for more information.

Abstract class and interface in programming

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 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.

Abstract class and interface from the design concept level

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 section analyzes the differences between abstract class and interface on the other layer. 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 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 ). 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:

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

Use the interface method to define the door:

Interface door {
Void open ();
Void close ();
}

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 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 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, 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 the interface method definition) 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 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 interface. 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. 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.

Conclusion

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 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 ). This is actually a common use of language. I hope readers can understand it in detail.

 

Three articles are transferred from http://space.flash8.net/space? 638324/action_spacelist_type_blog_itemtypeid_9345.html

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.