What is the difference between Java interfaces and abstract classes, when to use interfaces, and when to use abstract classes?

Source: Internet
Author: User

What is the difference between Java interfaces and abstract classes, when to use interfaces, and when to use abstract classes?

2013-01-05 17:16:09 |   Category:  java  |   Tags: java  | report | font size   subscription

Here's a comparison of the syntax differences between the two:
1Abstract classes can have construction methods, and interfaces cannot have constructors.
2There can be ordinary member variables in an abstract class, and there are no ordinary member variables in the interface.
3Abstract classes can contain non-abstract ordinary methods, and all methods in an interface must be abstract and cannot have non-abstract ordinary methods.
4. The access type of an abstract method in an abstract class can be public,protected and (the default type, although
Eclipse does not give an error, but it should not), but the abstract method in the interface can only be of the public type, and the default is the public abstract type.
5. Abstract classes can contain static methods, and interfaces cannot contain static methods
6. Both abstract classes and interfaces can contain static member variables, and the access types of static member variables in an abstract class can be arbitrary, but the variables defined in the interface can only be public static final types, and the public static final type is the default.
7.A class can implement multiple interfaces, but can inherit only one abstract class.
Let's talk about the difference between the two applications:
Interface is more in the system architecture design method to play a role, mainly used to define the communication contract between the modules. Abstract classes play a role in the implementation of code, can implement code reuse, for example, template method design pattern is a typical application of abstract class, it is assumed that all the servlet classes of a project to use the same way to determine permissions, log access logs and handle exceptions, you can define an abstract base class, Let all servlets inherit this abstract base class, complete the permission judgments, log access logs, and code to handle exceptions in the service method of the abstract base class, and only complete their own business logic code in each subclassThe following is collected from the network for reference only ... (1),Abstract class and interface are the two mechanisms in the Java language to support the definition of a class, and it is precisely because of the existence of these two mechanisms that it gives Java a powerful object-oriented capability. Abstract class and interface are very similar in terms of support for the definition of abstractions, and can even be replaced, so many developers are more likely to choose abstract classes and interface when they are doing the abstraction class definitions. In fact, there is a great difference between the two, for their choice even reflects the nature of the problem areas of understanding, the design intent of the understanding is correct, reasonable. This article will analyze the differences between them and try to provide a basis for developers to choose between them.

Understanding Abstract Classes

Abstract class and interface are used in the Java language for abstraction classes (the abstract class in this article is not translated from abstract class, it represents an abstract body, while abstract Class is a method of defining abstract classes in the Java language, which the reader is aware of, and what are abstract classes, and what are the benefits of using 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, and if a class does not contain enough information to depict a specific object, such a class is an abstract class. Abstract classes are often used to characterize the abstract concepts we derive from analysis and design of problem areas, and are abstractions of a series of concrete concepts that look different, but are essentially the same. For example, if we develop a graphical editing software, we will find that there are some specific concepts of circle and triangle in the problem domain, they are different, but they all belong to the concept of shape, the concept of shape does not exist in the problem domain, it is an abstract concept. Abstract classes used to characterize abstract concepts cannot be instantiated because abstract concepts have no corresponding specific concepts in the problem domain.

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 this group of behaviors can have any possible concrete implementation. This abstract description is an abstract class, and any possible concrete implementation of this group is represented by all possible derived classes. The module can manipulate an abstract body. Because the module relies on a fixed abstraction, it can be modified, and the behavior of this module can be extended by deriving from this abstraction. Readers familiar with OCP must know that abstract classes are key in order to achieve a core principle OCP (open-closed Principle) for object-oriented design.


On the abstract class and interface from the perspective of grammar 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-ABSTARCT member methods, and in the implementation of interface mode, the demo can only have static data members can not be modified (that is, must be static final , but the data members are not generally defined in interface, all the 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". However, there are some differences in the specific use.

First, the 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. 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. However, in the definition of interface, the method does not have the default behavior, and in order to circumvent this restriction, the delegate must be used, 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 (typically represented by an abstract class or interface) to accommodate the new situation (for example, adding new methods or adding new parameters to a used method), it can be very cumbersome and may take a lot of time (for many of the derived classes , in particular). However, if the interface is implemented by an abstract class, it is possible to modify the default behavior defined in the abstract class only.

Similarly, if the default behavior cannot be defined in an abstract class, it causes the same method implementation to appear in each of the derived classes of the abstract class, violating the "one Rule,one place" principle, resulting in code duplication, which is also detrimental to future maintenance. Therefore, you should be very careful when choosing between the abstract class and the interface.


Abstract class and interface from the perspective of design concept

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 examines the difference between the two, from another level: the design concepts reflected by the abstract class and interface. The author thinks that the analysis from this level can understand the essence of the two concepts.

As mentioned earlier, ABSTARCT class embodies an inheritance relationship in the Java language, in order to make the inheritance relationship reasonable, there must be an "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 (the reference (3) is about "is a" In-depth discussion of the relationship, interested readers can refer to). For interface, it does not require that the interface and interface definitions be consistent in the concept, but only the 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 there is an abstraction about door in our problem area, that the door has the ability to execute two actions open and close, at which point we can define a type that represents the abstract concept by either an abstract class or a interface. The definitions are as follows:

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 seems that there is no big difference between using 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 difference between the abstract class and the interface reflected in the design concept, the other aspects of the problem are simplified or ignored)? Here is a list of possible solutions and the analysis of these different scenarios from the design concept level.

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 priciple), which mixes the behavior method inherent in door concept with another concept of "alarm" in the definition of door. One problem is that modules that rely solely on the concept of door are changed by the concept of "alarm" (e.g., 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. These two concepts are defined using the abstract class approach, both of which are defined using the interface method, one defined using the abstract class approach, and the other defined using the interface method.

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 latter two methods are feasible, but the choice of them reflects the understanding of the conceptual nature of 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 in the concept is essentially door or alarm? 2. If our understanding of the problem area is not problematic, for example: we find that Alarmdoor is consistent in concept in nature and door by analysis of the problem domain, then we do not have the right to reveal our design intent when we implement it. Because the definitions of the two concepts, which are defined using the interface method, do not reflect the above meanings.

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 we mean? As already mentioned, abstract class represents an inheritance relationship in the Java language, whereas an inheritance relationship is essentially an "is a" relationship. So for the door concept, we should use the ABSTARCT class approach to define it. 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 way. As shown below:

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 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 a "like a" relationship, you can choose as a basis, of course, this is based on the understanding of the problem areas, For example: If we think that alarmdoor in the concept is essentially an alarm, but also has the function of door, then the definition of the above method will be reversed. (2),Interfaces and abstract classes follow the design principle of "write code not for implementation," which is designed to increase the flexibility of the code to cope with changing requirements.
In Java, you can inherit only one class, but implement multiple interfaces. So when you inherit a class, you can't inherit another class.
Interfaces are used to represent adjectives or behaviors, such as runnable, Clonable, Serializable, and so on. Therefore, if you use an abstract class to define (implement) Runnable and clonacle, you cannot enable your class to implement this

Two functions, and if the interface is not a problem.
Abstract classes are slightly faster than interfaces, so applications that care about time use abstract classes as much as possible.
Abstract classes are a better choice if the common behavior of multiple inheritance hierarchies is better written in the same place. Sometimes it is possible to define functions in an interface, but in an abstract class the default functionality enables interfaces and abstract classes to work together.
Design a concurrency rule pipeline in Java?
Concurrent programming and concurrent design are hot because it makes more efficient use of today's increasingly advanced processors, and Java is considered a multithreaded language for this reason. The key to designing a concurrency system is thread-safe, non-volatile

Local variables, and avoid using local variables and instance variables. You only need to ensure that multiple threads can execute the same class at the same time, so the best solution is for each thread to operate only its own data, using the smallest possible synchronization

, especially at the beginning of the pipeline. This can be done from the initial discussion to the finalization of the class and interface, but as long as you remember to pay attention to the key to concurrency issues, such as competitive state, deadlock, memory conflict, atomic operation, threadlocal change

And so on, try to circumvent these problems.
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. In abstract class, you can have your own data members, or you can have non-ABSTARCT member methods, and in interface, you can only have static data members that cannot be modified (that is, it must be static final, but

Data members are not generally defined in interface, and 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 the "like-a" relationship.

4. Classes that implement abstract classes and interfaces must implement all of these methods. Abstract classes can have non-abstract methods. There is no implementation method in the interface.

5. The variable defined in the interface is the public static final type by default, and must be given its initial value, so the implementation class cannot be redefined or changed.

6. Variables in abstract classes are friendly by default, whose values can be redefined in subclasses or re-assigned.

7. The methods in the interface are public,abstract type by default.

The difference between super and this + interface and abstract class:
1.super can be interpreted as a reference to the parent class object, which can be used in subclasses to invoke the overridden party in the parent class.
method or variable. This can be understood as a reference to an object of its own, and a method or variable in the same class can be called.
2. Static variables and static methods are classes, that is, you can use the class to call without a new object,
Static variables have only one copy in memory, and all instances of the class share static variables.
3. Inheritance uses the Extends keyword implementation, Eg:class Dog extends animal{}.
4. The difference between an interface and an abstract class:
1. The interface embodies a specification, the abstract class embodies the template-style design.
2. The methods in the interface are all abstract methods, and the abstract class can be implemented in a method.
3. Static methods cannot be defined in an interface, and can be in an abstract class.
4. The variables in the interface are all static constants, and there can be ordinary variables in the abstract class.
5. There can be no constructors and initialization blocks in the interface, which can be found in the abstract class.
6. A class can implement multiple interfaces, but can inherit only one abstract class.

"An interface is a fully abstracted collection of members that cannot be implemented at the interface definition, and we can treat it as defining the contract for the operation, and the implementation of the interface is left entirely to the developer." The difference between them, if carefully analyzed, or

There are quite a few: in Java, a class can only inherit from a base class, so if you want to use an abstract class to provide polymorphism for a set of classes, the classes must all inherit from that class, and the interface is not the same, it can not only use a class or structure to

Now multiple interfaces, an interface can have multiple implementations. ”

An abstract class is a class that cannot be instantiated and must inherit from it. Abstract classes can be fully implemented, but more commonly, partial implementations, or not at all, encapsulate the common functionality of inheriting classes, which can provide implemented members, so you can

Use an abstract class to ensure a specific number of identical functions, but you cannot do so with an interface.
"In other words, they differ in the question of providing polymorphism.

There is a common design idea, if you want to design a small and concise function block, then use the interface. If you are designing large functional units, use an abstract class. ”

The interface can be a useful tool if used appropriately. But if used improperly, they can become very tricky and even hinder effective programming. The design and use of the interface is actually a brilliant art. ”

"Through the interface and implementation, we can use the same type of program on different objects, and do not have to modify the original class, relative subroutines must be modified by the source code to achieve the purpose of reuse, interface and implementation not only

is a great progress, but also a very high level of procedural design art. ”

Interface is a very effective programming method that separates object definition from implementation so that objects can be perfected and evolved without destroying existing applications. Interface eliminates a major problem in implementing inheritance,

The code is likely to be corrupted when it is implemented and then changed. Even if implementing inheritance allows classes to inherit implementations from the base class, the first time the class is released will still make us have to make a lot of choices for the design. If the original assumption is incorrect, it is not

You can always make security changes to your code in a future release. For example, we define a method for a base class that requires an Integer parameter, and later determines that the parameter should be a Long data type. We cannot safely change the original

Class, because an application that is designed for a class that derives from the original class may not compile correctly. This problem can be magnified because a single base class affects hundreds of subclasses. ”

With an application that requires many potentially unrelated object types to provide some functionality, the interface is more adaptable and the interface is more flexible than the base class because a single implementation can be defined to implement multiple interfaces, without inheriting from the base class

, interfaces are better, and interfaces are useful in situations where class inheritance cannot be used. For example, structs cannot inherit from classes, but they can implement interfaces. ”

"But the biggest problem is focusing on the interface design. Once an interface is defined and accepted, it must remain intact to protect applications written for use with that interface. After the interface is published, it cannot be changed. This is what we do

An important principle of component design, called ' Interface invariance '. ”
Creating an interface is the creation of a definition that can never be changed after the interface definition is published. Interface invariance is to protect an existing system that is written to use the interface. When the interface design and requirements differ, it is necessary to make a significant change

Even more, we should create a new interface. You may also like:
    • Java face question
    • The 150++ of Java Programmer interview
    • Java generics explained (generic, wildcard, generic interface)
    • Java memory allocation mechanism
    • How to understand multithreaded java-thread (inheriting the thread class, implementing the Runnable Interface)
    • The Java written test topic of the EE written topic servlet written questions jsp written questions
    • A little idea of user role permissions
    • Java Interface Programming Benefits: Where are the benefits and benefits?
    • What is the core mechanism of dependency injection--spring introduction to Dependency Injection
    • Java memory
    • Interview Highlights (Collection Framework): Summary of Java Collection Framework usage
    • Java Concurrency: Thread-safe programming needs attention

What is the difference between Java interfaces and abstract classes, when to use interfaces, and when to use abstract classes?

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.

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.