Java abstract classes and interfaces collation

Source: Internet
Author: User
Tags define abstract

    • Java defines some methods that do not contain the method body, the implementation of the method body to the subclass of the class according to their own circumstances to implement, such a method is an abstract modified method of abstraction, including the abstract method of the class is called abstract class, with the abstraction modified
    • Abstract method:

abstract [modifier] < return type > method name ([parameter table]);

Note: The last punctuation is ";", no curly braces! Adding braces means you are going to implement this method, but the abstract method cannot have a body! No need to implement! Just declare it.

    • All specific subclasses of an abstract superclass must provide a concrete implementation for the hyper-tired abstract method.
    • Abstract class:

There is one or more abstract methods that can have a general approach

Must be an abstract decoration!

[public] abstract class name

A static method cannot be an abstract method!

    • Abstract methods must be overridden, and abstract classes must be inherited.
    • Abstract classes cannot be instantiated directly, but are typically super-classes of other classes. Use an abstract class to declare a variable that holds a reference to an object of any specific class that is derived from the abstract class. Programs typically manipulate subclass objects by using this variable in a polymorphic way, as opposed to final.
    • To extend an abstract class:

Abstract class A {}

Abstract public B extends A {}

When some methods of the parent class are not deterministic (abstract method),

Class that contains the abstract modifier is an abstract class, and the abstract class cannot create an instance object, and the classes containing the abstract method must be defined as abstract class, and the method in the abstract class does not have to be abstract. Abstract to define abstract methods must be implemented in a specific subclass, so ah, there can be no abstract constructor method or abstract static method, if the subclass does not implement all the methods in the abstract parent class, then the subclass must also be defined as an abstract class.

Interface (interface) can be said to be a special case of abstract classes. All methods in an interface must be abstract, and the method definition in the interface defaults to public abstract. The variables in the interface are global constants, which are public static final adornments.

Look at their grammatical differences!

1, the abstract class can have a construction method, and the interface cannot have a construction method.

2, abstract classes can have ordinary member variables, and interfaces cannot have ordinary member variables.

3, abstract classes can contain non-abstract ordinary methods, and all the methods in the interface must be abstract, not a non-abstract ordinary method.

4, the access type of an abstract method in an abstract class can be public, protected, and the default type, but the abstract method in the interface is only public type, and the default is the public abstract type.

5, a static method can be included in an abstract class, and a static method cannot be contained within an interface.

6, the abstract class and interface can contain static member variables, the access type of static member variables in the abstract class can be arbitrary, but the variables defined in the interface can only be public static type, and the default is the public static type.

7, a class can implement multiple interfaces, but can inherit only one abstract class.

Add the difference between the two in the application:

Interface is more in the system framework design method to play a role in the main definition of communication between modules, and abstract classes in the implementation of code to play a role, you can implement code reuse

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.

    • Problem:

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

Class Alarmdoor extends Door {
void Open () {...}
void Close () {...}
void alarm () {...}
}

What difference does it have in terms of design?

From language specification's point of view, this article is also seen, but from the programmer, the developer's point of view, still no clear answer: When should use the interface, when should use the abstract class. If you are a java/c# programmer with one year of experience, you may have been "feeling" the difference but are not clear about it. I'm trying to make it clear here.
1. From the hierarchical structure of the class, abstract classes are usually at the top of the hierarchy, but in practical design practice, abstract classes should be the last to emerge. Why? In fact, abstract class acquisition is a bit like the extraction of mathematics common divisor: ax+bx+cx,x is abstract class, if you do not have the previous formula, how do you know if x is common divisor? At this point, it is also in line with the process of understanding the world, first concrete and then abstract. So in the design process if you get a lot of concrete concepts and find their commonalities from them, the set of commonalities is that abstract classes should be right.
2. interface, on the surface, is very similar to abstract classes, but the usage is completely different. Its basic function is to bring together some unrelated classes (concepts) to form a new, centrally manipulated "new class". One of the typical examples I give to students is "driver". Who can be a driver? Anyone can, just pick up the driver's license. So I don't care if you are a student, white collar, blue collar or boss, as long as you have a driver's license.
Interface Driverlicence {
Licence getlicence ();
}

Class Studentdriver extends Student implements Driverlicence {
}
Class Whtiecollaremployeedriver extends Whtiecollaremployee implements Driverlicence {
}
Class Bluecollaremployeedriver extends Bluecollaremployee implements Driverlicence {
}
Class Bossdriver extends Boss implements Driver {
}

When I define the "car" class, I can specify "driver".

Class Car {
Setdriver (driverlicence driver);
}
At this time, car objects do not care what the driver is doing, the only thing they have in common is to get a driver's license (all implemented the Driverlicence interface). This, should be the most powerful place of the interface is also the abstract class incomparable.

Summary: Abstract classes are common divisor that extract specific classes, and interfaces are meant to "hash" some unrelated classes into a common group. As for their syntax in each language, the details of the language are not my main concern.

Java abstract classes and interfaces collation

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.