Java improve the abstract class and interface of the article

Source: Internet
Author: User
Tags class definition

interfaces and inner classes provide us with a more structured approach to separating interfaces from implementations.

Abstract classes and interfaces are two mechanisms for defining abstract concepts in the Java language, and it is their presence that gives Java a powerful object-oriented capability. The support for abstract concepts between them is very similar, even interchangeable, but there are differences. one, abstract class

We all know that in an object-oriented domain everything is an object, and all objects are described by classes, but not all classes describe objects. If a class does not have enough information to describe a specific object, and other specific classes are required to support it, then such a class is called an abstract class. For example, New Animal (), we all know that this is the creation of an animal Animal object, but this Animal exactly what it looks like we do not know, it does not have a specific concept of animals, so he is an abstract class, need a specific animal, such as dogs, cats to make a specific description of it , we know what it's like.

Abstract classes that represent abstract concepts cannot be instantiated because abstract concepts do not correspond to specific concepts in the domain of problems in the object-oriented domain.

At the same time, abstract class embodies the idea of data abstraction, which is a mechanism to realize polymorphism. It defines a set of abstract methods, and the concrete representations of this set of abstract methods are implemented by derived classes. At the same time, abstract classes provide the concept of inheritance, and its starting point is to inherit, otherwise it does not exist any meaning. Therefore, the definition of the abstract class must be used to inherit, while in an abstract class as a node in the hierarchy chain of inheritance, the leaf node must be a specific implementation class. (I wonder if it's wrong to understand!!! Expert advice ...)

There are a few things to note when using abstract classes:

1, the abstract class can not be instantiated, the instantiation of the work should be to its subclasses to complete, it only needs to have a reference.

2. Abstract methods must be overridden by subclasses.

3, as long as an abstract class that contains an abstract method, the method must be defined as an abstract class, whether or not there are other methods included.

4, the abstract class can contain specific methods, of course, can not include abstract methods.

5. An abstract method in a subclass cannot have the same name as an abstract method of a parent class.

6. Abstract cannot modify the same class as final.

7. Abstract cannot modify the same method with private, static, final or native. 、

Instance:

Define an abstract animal class animal, provide abstract methods called Cry (), cats, dogs are subclasses of animal classes, because cry () is an abstract method, so cat, dog must implement the Cry () method. As follows:


It is useful to create abstract classes and abstract methods because they can make the abstraction of the class clear and tell the user and the compiler how they intend to use them. Abstract classes are also useful refactorings because they allow us to easily move the public approach up the inheritance hierarchy. (From:think in Java) second, interface

An interface is a "class" that is more abstract than an abstract class. I can't find a better word for "class" here, but let's be clear that the interface itself is not a class, as can be seen from the fact that we cannot instantiate an interface. If the new Runnable () is definitely wrong, we can only new its implementation class.

Interfaces are used to establish a protocol between classes, and it provides only a form, not a concrete implementation. The implementation class that implements the interface must implement all the methods of the interface, and by using the Implements keyword, he indicates that the class is following a particular interface or a set of interfaces, while also indicating that "interface is just its appearance, but it now needs to declare how it works".

Interface is an extension of the abstract class, Java to ensure that data security can not be multiple inheritance, that is, inheritance can only exist a parent class, but the interface is different, a class can implement multiple interfaces, regardless of the relationship between these interfaces, so the interface makes up for the abstract class can not be multiple inheritance defects However, it is recommended that inheritance and interfaces be used together, as this guarantees both data security and multiple inheritance.

There are several issues to be aware of when using interfaces:

1, a interface party all the legal access rights are declared as public automatically. It's only public, of course, and you can show the declaration as protected, private, but the compilation will go wrong.

2, the interface can be defined as "member variable", or immutable constants, because the interface of the "member variable" will automatically become public static final. You can name direct access through a class: Implementclass.name.

3, there is no way to implement in the interface.

4. A non-abstract class that implements an interface must implement all the methods of that interface. Abstract classes can be implemented without implementation.

5. You cannot instantiate an interface using the new operator, but you can declare an interface variable that must reference (refer to) An object that implements the interface's class. You can use instanceof to check whether an object implements a particular interface. For example: if (anobject instanceof comparable) {}.

6, in the implementation of multiple interfaces must avoid the repetition of the method name. Iii. The difference between abstract classes and interfaces

Although there are larger similarities between abstract classes and interfaces, and sometimes they can be interchanged, this does not make up for the difference between them. The abstract classes and interfaces are described in two aspects of the syntax level and design hierarchy below. 3.1 Grammatical Hierarchy

At the syntactic level, the Java language gives different definitions for abstract classes and interfaces. Here are the demo classes to illustrate the differences between them.

Use abstract classes to implement:


Using interfaces to implement

Abstract class method, an abstract class can have any range of member data, you can also have your own Non-abstract method, but in an interface way, it can only have static, unmodified member data (but we typically don't use member data in an interface), and all of its methods must be abstract. In some ways, interfaces are specialized for abstract classes.

In the case of a subclass, it inherits only one abstract class (which is considered by Java for Data security), but it can implement multiple interfaces. 3.2 Design Level

The above is only from the grammatical level and programming point of view of the relationship between them, these are low-level, in order to really use a good abstract class and interface, we must be from a higher level to distinguish. Only from the angle of design concept can we see the essence of them. In general they exist as follows three different points:

1. Different levels of abstraction. An abstract class is an abstraction of a class, whereas an interface is an abstraction of the behavior. An abstract class is an abstraction of the whole class as a whole, including attributes, behavior, but an interface that abstracts the local (behavior) of the class.

2. Different across domains. An abstract class spans a class that has similar characteristics, whereas an interface can have different classes across domains. We know that an abstract class discovers a common part from a subclass, then generalizes it to an abstract class, and the subclass inherits the parent class, but the interface is different. The subclass that implements it can have no relationship, in common. For example, cats and dogs can be abstracted into an abstract class of animals, with a method called. Birds, aircraft can achieve the fly fly interface, with flying behavior, here we can not be a bird, the aircraft share a parent class bar. So the abstract class embodies an inheritance relationship, and there must be a "is-a" relationship between the parent class and the derived class in order for the inheritance relationship to be reasonable, that is, the parent class and the derived class should be identical in concept. For an interface, it does not require that the implementation of the interface and the interface definition are essentially consistent in concept, but only the contract that implements the interface definition.

3, the design level is different. For abstract classes, it is designed from the bottom up, we have to know the subclass to abstract the parent class, and the interface is different, it does not need to know the existence of subclasses, only need to define a rule, as to what subclasses, when how to achieve it all do not know. For example we have only one cat in here, if you are this is to abstract into an animal class, is not a bit excessive design. We must have at least two animals, cats and dogs here, we abstract their similarities in order to form an animal abstract class it. Therefore, abstract classes are often reconstructed by refactoring. But the interface is different, for example, fly, we simply do not know what will be the implementation of this fly interface, how to realize also unknown, we have to do is to define a good flight behavior interface. So the abstract class is abstracted from the bottom up, and the interface is designed from the top down.

We have a door abstract concept that has two behaviors open () and close (), at which point we can define this abstract concept through abstract classes and interfaces:

Abstract class:


Interface

As for other specific classes that can be defined by using an abstract class method with extends or implements using an interface method to define door, there is no significant difference between the two.

But now if we need the door to have the alarm function, then how to achieve it.

Solution One: Add an alarm method to door: Clarm ();


Or

This approach violates one of the core principles of object-oriented design ISP (Interface segregation principle)-see annotations, in the definition of door, the door concept itself is inherent in the behavior and another concept of the "alarm" behavior method mixed together. One problem with this is that the modules that rely solely on the concept of door will change as the concept of "alarm" changes, and vice versa.

Solution Two

Since open (), close (), and alarm () are two different concepts, we define them separately in two abstract classes representing two different concepts in terms of the ISP principle, in three ways:

1, two are defined using an abstract class.

2, two are defined using an interface.

3, one uses the abstract class definition, one is uses the interface definition.

Because Java does not support multiple inheritance, the first is not feasible. The following two are all feasible, but choosing what reflects your understanding of the nature of the problem domain.

If you choose the second interface to define, then it reflects two questions: 1, we may not understand the problem domain, Alarmdoor in the concept of essentially the door also alarm. 2, if we have no problem understanding of the problem domain, for example, we have identified in the analysis of the alarmdoor in the fundamental concept is consistent, then we are not in the design of the correct reflection of our design intent. Because you use two interfaces to define them, the definition of their concepts does not reflect the above meaning.

Third, if our understanding of the problem domain is this: Alarmdoor is inherently door, but it also has the behavioral function of alerting, this time we use a third scenario to illustrate our design intent. The essence of Alarmdoor is that we use abstract classes to define this concept, and Alarmdoor has the function of alerting that it can complete the behavioral functions defined in the alarm concept, so alarm can be defined using interfaces. As follows:


This way of implementation can basically clearly reflect our understanding of the problem area and correctly reveal our design intent. In fact, the abstract class represents a "is-a" relationship, the interface represents the "like-a" relationship, which can be used as a basis when choosing, of course it is based on the understanding of the problem area, for example: if we think that Alarmdoor is essentially an alarm in concept and has door function, So the way this is defined is in turn.

Comments:

ISP (Interface segregation principle): an object-oriented core principle. It shows that using multiple specialized interfaces is better than using a single total interface.

The dependency of a class on another class should be based on the smallest interface.

An interface represents a role and should not be assigned to an interface with different roles. Interfaces that do not have a relationship are merged to form a bloated, large interface that is polluting the roles and interfaces. Iv. Summary

1. An abstract class represents an inheritance relationship in the Java language, where only one parent class exists, but multiple interfaces can exist.

2, in the abstract class can have its own member variables and Non-abstract class methods, but the interface can only have static immutable member data (but generally do not define the member data in the interface), and all of its methods are abstract.

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

Abstract classes and interfaces are two different abstract concepts in the Java language, and their presence provides very good support for polymorphism, although there is a great similarity between them. But their choices often reflect your understanding of the problem domain. Only a good understanding of the nature of the problem domain can make a correct and reasonable design.

Consolidate the foundation, improve technology, do not fear difficulties, climb the peak ...

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.