Abstract classes and interfaces for the Java Foundation

Source: Internet
Author: User
Tags class definition

Interfaces and internal 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. Their support for abstract concepts is very similar and even interchangeable, but there are differences.

First, abstract class

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

Abstract classes used to characterize abstract concepts cannot be instantiated in the object-oriented domain because abstract concepts have no corresponding specific concepts in the problem domain.

At the same time, abstract class embodies the idea of data abstraction and is a mechanism to realize polymorphism. It defines a set of abstract methods that are implemented by a derived class for the specific representation of this set of abstract methods. At the same time, abstract classes provide the concept of inheritance, the starting point is to inherit, otherwise it does not exist any meaning. Therefore, the definition of the abstract class must be used to inherit , at the same time in an abstract class as a node of the inheritance relationship hierarchy chain, the leaf node must be a specific implementation class.

There are a few things to keep in mind when using abstract classes:

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

2. Abstract methods must be overridden by subclasses.

3. As long as an abstract class containing 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 contain abstract methods.

5. Abstract methods in subclasses cannot have the same name as the abstract methods of the parent class.

6. Abstract cannot be modified in the same class as final.

7. Abstract cannot be modified with private, static, final, or native the same method. ,

Instance:

Define an abstract animal class animal, which provides an abstract method called Cry (), a cat, a dog is a subclass of animal class, because cry () is an abstract method, so cat, dog must implement the Cry () method. As follows:

Public abstract class Animal {public    abstract void Cry ();} public class Cat extends animal{    @Override public    void Cry () {        System.out.println ("Cat: Meow ...");    } public class Dog extends animal{    @Override public    void Cry () {        System.out.println ("Dog bark: Bark ...");    } public class Test {public    static void Main (string[] args) {        Animal a1 = new Cat ();        Animal A2 = new Dog ();                A1.cry ();        A2.cry ();    }} --------------------------------------------------------------------Output: Cat's name: Meow meow ... Dog Bark: Bark ...

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

Second, the interface

An interface is a "class" that is more abstract than an abstract class. The quote for "class" Here is that I can't find a better word to say, but let's be clear that the interface itself is not a class, as we can see from the fact that we can't instantiate an interface. such as new Runnable (); It must be wrong, we can only new its implementation class.

An interface is used to establish a protocol between classes, which provides only a form, without a specific implementation. The implementation class that implements the interface must implement all the methods of the interface, by using the Implements keyword, he says that the class is following a particular interface or a specific set of interfaces, and that "interface is just the way it looks, but now you need to declare how it works."

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

There are several issues to be aware of when using the interface :

1, interface All laws access rights are automatically declared aspublic. Only public, of course, you can display the declaration as protected, private, but the compilation will be wrong!

2, the interface can be defined as "member variables", or immutable constants, because the interface in the "member variable" will automatically become public static final. Direct access is possible through the class name: Implementclass.name.

3, There is no method of implementation in the interface.

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

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

6, in the implementation of multi-interface must avoid the repetition of the method name.

Three, the difference between abstract class and interface

Although there are large similarities between abstract classes and interfaces, and sometimes even interchangeable, this does not compensate for their differences. Abstract classes and interfaces are described in the following two aspects, from the syntax level and the design level.

3.1 Syntax levels

At the syntax level, the Java language has different definitions for abstract classes and interfaces. The following are the demo classes to illustrate the differences between them.

Use abstract classes to implement:

Public abstract class Demo {    abstract void method1 ();            void Method2 () {        //implementation    }}

Using interfaces to implement

Interface Demo {    void method1 ();    void Method2 ();}

Abstract class mode, the abstract class can have any range of member data, but also can have their own non-abstract methods, but in the interface mode, it can only have static, cannot modify the member data (but we generally do not use member data in the interface), and all of its methods must be abstract. In a way, an interface is a specialization of an abstract class.

In the case of a subclass, it can inherit only one abstract class (which is considered by Java for Data security), but it implements multiple interfaces.

3.2 Design Levels

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

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

2, cross-domain different. An abstract class spans a class that has similar characteristics, whereas an interface can span different classes of domains . We know that the abstract class is discovering the public part from the subclass, and then generalizing it into 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, airplanes can achieve flying fly interface, with the behavior of flying, here we can not be birds, airplanes share a parent class bar! So the abstract class embodies an inheritance relationship, 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 an interface, it does not require that the implementation of the interface and the interface definition are inherently consistent in concept, but only the contract that implements the interface definition.

3, the design level is different. For the abstract class, it is designed from the bottom up, we have to know the subclass to abstract out 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 sub-class, when how to implement it all do not know. For example, we only have a cat class here, if you are abstract into an animal class, is not the design a bit excessive? We have at least two animals, cats, dogs here, we are in the abstract what they have in common to form an animal abstract class it! So, abstract classes are often reconstructed by refactoring! But the interface is different, for example fly, we do not know what will be to achieve this flight interface, how to realize it is not known, we have to do is to define the pre-flight behavior interface. So the abstract class is a bottom-up abstraction, and the interface is designed from the top down.

( above is purely personal opinion, such as discrepancies, errors, hope you point!!!!) )

To better illustrate the differences between them, an example will be used to illustrate them. This example is quoted from: http://blog.csdn.net/ttgjz/article/details/2960451

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

Abstract class:

Abstract class door{    abstract void Open ();    abstract void Close ();}

Interface

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

As for the other specific classes can be defined by using extends abstract class door or implements use interface way 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 implement it?

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

Abstract class door{    abstract void Open ();    abstract void Close ();    abstract void alarm ();}

Or

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

This approach violates a core principle in object-oriented design. ISP (Interface segregation Principle)-see annotations, which mix the behavior methods inherent in the door concept itself 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", and vice versa.

Solution II

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

1, two are defined using an abstract class.

2, two are defined using an interface.

3. One uses an abstract class definition, and one is defined with an interface.

Because Java does not support multiple inheritance, the first is not feasible. The next two kinds are feasible, but the choice reflects your understanding of the nature of the problem domain.

If the choice of the second is an interface to define, then it reflects two questions: 1, we may not understand the problem domain, Alarmdoor in the concept is essentially a door alarm. 2, if our understanding of the problem domain is not a problem, for example, when we analyze the definition of alarmdoor in the nature of the concept is consistent, then we do not correctly reflect the design of the design intent. Because you use two interfaces to define them, the definition of their concepts does not reflect the above meanings.

Third, if our understanding of the problem domain is this: Alarmdoor is inherently door, but it also has the function of alerting, this time we use the third scenario to illustrate our design intent. Alarmdoor essence is, so for this concept we use abstract class to define, while Alarmdoor has the alarm function, it can complete the alarm concept defined in the behavior function, so alarm can use the interface to define. 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 kind of realization basically can clearly reflect our understanding of the problem area, and reveal our design intention correctly. Its real abstract class represents the "is-a" relationship, the interface represents the "like-a" relationship , you can choose as a basis, of course, this is based on the understanding of the problem domain, such as: if we think that alarmdoor in the concept is essentially an alarm, At the same time has the function of door, then the definition of the above will be reversed.

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 different roles should not be handed over to an interface. Interfaces that are not related are combined to form a bloated, large interface that is polluting the roles and interfaces.

Iv. Summary

1, abstract class in the Java language represents an inheritance relationship, a subclass can only exist one parent class, but there may be more than one interface.

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

3, the abstract class and the interface reflects the design concept is different, the abstract class represents is "is-a" the relation, but the interface represents is "the like-a" the relation.

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 for their choices, it often reflects your understanding of the problem domain. Only a good understanding of the nature of the problem domain can make the correct and reasonable design.

Transfer from https://www.cnblogs.com/chenssy/p/3376708.html

Abstract classes and interfaces for the Java Foundation

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.