interface and abstract class Java

Source: Internet
Author: User
Tags comparable


Abstract class and interface are the two mechanisms in the Java language that support the definition of a class, and it is precisely because of the existence of these two mechanisms that the powerful object-oriented capabilities of Java are given, and there are similarities between them, but there are many differences in actual usage.

1. Abstract class

In object-oriented concepts, all objects are described by a class, but conversely not, 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.

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.

The abstract class is defined as: a class containing abstract methods;

Public abstract class ClassName {    abstract void Fun ();}

abstract methods: only declarations, without specific implementations, are in the form of abstract methods:

    abstract void fun ();

abstract methods must be decorated with the abstract keyword. If a class contains abstract methods, it is called an abstract class, and the abstract class must be decorated with the abstract keyword before the class. because abstract classes contain methods that are not specifically implemented, you cannot create objects with abstract classes.

A class that contains an abstract method is called an abstract class, but it does not mean that there can be only abstract methods in an abstract class, which, like normal classes, can also have member variables and ordinary member methods. Note that there are three main differences between abstract and ordinary classes:

1) The abstract method must be public or protected (because if you are private, you cannot inherit from the quilt class, the subclass cannot implement the method), and by default it is public.

2) Abstract classes cannot be used to create objects;

3) If a class inherits from an abstract class, the child class must implement the abstract method of the parent class. If the subclass does not implement an abstract method of the parent class, the subclass must also be defined as an abstract class.

In other respects, there is no difference between an abstract class and an ordinary class.

2. Interface 2.1 Definition related

An interface means: "All classes that implement that particular interface look like this." So any code that uses a particular interface knows which methods of the interface can be called, and only needs to know, that the interface is used to establish the protocol between classes. But interface is not just an extremely abstract class, because it allows people to implement features like multiple inheritance variants by creating a type that can be transformed upward into multiple base classes.

[Public] interface InterfaceName {}
the interface can contain variables and methods. Note, however, that the variables in the interface are implicitly specified as public static final variables (and can only be public static final variables, which are reported as compilation errors with private adornments), and methods are implicitly specified as public Abstract method and can only be public abstract method (with other keywords, such as private, protected, static, final and so on will be reported compile errors), and the interface of all methods can not have a concrete implementation, that is to say, The methods in the interface must all be abstract methods. From here we can see the difference between interface and abstract class, interface is an extremely abstract type, it is more "abstract" than abstract class, and generally does not define variables in the interface.

To have a class follow a specific set of interfaces requires the use of the Implements keyword, in the following format:

Class ClassName implements interface1,interface2,[....] {}

As an interface, a class can inherit from the interface (or implement the interface), which is also multi-inheritance, the interface member variables are not exclusive to an object, are static member variables, belong to the entire class, so a class to implement multiple interfaces is irrelevant, there will be no conflicting objects between the problem. Implementation of multiple interfaces, but also to achieve multiple inheritance, but also to avoid multiple inheritance prone to problems, which is the use of interfaces to achieve multiple inheritance benefits.
 2.2 Meaning of the separation interface

We used the interface, but the interface didn't reduce the amount of work we had when we defined the class. We still have to write the class exactly as before. We should be even more careful not to violate the interface rules. So why should we use interface?

In fact, interface is like an industry standard . A factory (class) can adopt the industry standard (implement Interface), or it can not adopt the industry standard. However, a product that incorporates industry standards will have the following benefits:

    • Higher quality: Cups that do not have a water-adding function do not meet the standard.
    • Easier to promote: like a USB interface on a computer, downstream products can be more easily bridged.

If we already have a Java program that handles objects that match the CPU interface, such as picking a child to drink. So, as long as we are sure, we give the child's Cup (object) to implement a cup interface, you can ensure that children can perform water this action. As for how the Cup (object) defines the action of drinking water, we can leave it to the appropriate class to decide (for example, to drink water with a straw, or to open a small mouth to drink water).

In computer science, interfaces are very important concepts. For example, any operating system that provides UNIX interfaces can be called UNIX systems. Linux,mac Os,solaris are UNIX systems that provide similar interfaces. However, the specific implementation of each system (source code) is different. Linux is open source and you can see every line of code, but you still don't know how to write a Solaris system.

2.3 For example, the solution

I know comparable this interface is used to compare two objects, so how to compare?

numbers have numeric comparisons, strings have a comparison of strings, and students (classes of their own definition) also have their own comparative side law. Then, in another code that is responsible for the ordering of objects (not necessarily numbers), you must compare two objects.
What are the types of these two objects? Object A, B? Certainly not, a > B syntax like this cannot be compiled. int A, b? Or not? In the beginning, it's not necessarily a number.

so, comparable is coming. He tells the compiler that a B two objects all satisfy the comparable interface, that is, they can be compared. Specifically, this procedure does not need to be known. So, he needs some concrete implementations, the comparable interface has a method called CompareTo. Then this method is used to replace operators such as <, >. This is because the operator is reserved for comparison with built-in types (integers, floating-point numbers) rather than a generalized comparison operation.

If you can understand an existing interface such as comparable in the JDK's own library, it is easy to understand why you need to use the interface when developing the program.


Programming is oriented towards abstraction (interface). There are many advantages to doing so, and in the case of the most votes, the procedure can be expanded. When you modify your specific implementation class (or add a new implementation Class), you do not need to modify the class that invokes it, which is the "open to expand, close to modify" principle that is emphasized in Java programming. In design mode, many of them need to use interfaces. Of course, this is also the embodiment of Java polymorphism.

the second is that Java implements multiple inheritance through interface. One of the benefits of inheritance is the reuse of code, which reduces code errors. In this, the interface is equivalent to a specification, that is, to implement this interface, you have to implement the method of the interface, to complete the corresponding functions. If there is no interface, then it is possible to omit the method, or the method of definition is not uniform, when implemented.

3. Interface and abstract class differences 3.1 syntax level

1) Abstract classes can provide implementation details of member methods, and only public abstract methods exist in interfaces;

2) member variables in an abstract class can be of various types, whereas member variables in an interface are only public static final types;

3) The interface cannot contain static code blocks and static methods, while abstract classes can have static code blocks and static methods;

4) A class can inherit only one abstract class, while a class may implement multiple interfaces.


3.2 Design Level

1) Abstract class is an abstraction of a thing, that is, an abstraction of a class, and an interface is an abstraction of a 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. For a simple example, airplanes and birds are different kinds of things, but they all have a common denominator, that is, they can fly. Then in the design, the aircraft can be designed as a class airplane, the bird is designed as a class bird, but not the characteristics of the flight is also designed as a class, so it is only a behavioral characteristics, not a kind of abstract description of things. At this point the flight can be designed as an interface fly, including the method fly (), and then airplane and bird respectively according to their own needs to implement the fly this interface. Then as for the different types of aircraft, such as fighter jets, civil aircraft, such as direct inheritance airplane can, for birds is similar, different species of birds directly inherit the bird class can be. As can be seen from here, inheritance is a "is not" relationship, and the interface implementation is "there is no" relationship. If a class inherits an abstract class, then the subclass must be the kind of abstract class, and the implementation of the interface is there is no, with no relationship, such as whether the bird can fly (or whether it has the characteristics of flight), can fly can realize this interface, not flying will not implement this interface.

2) The design level is different, abstract class as the parent class of many subclasses, it is a kind of template design. And the interface is a kind of behavior specification, it is a kind of radiant design. What is a template design? The simplest example, we have used the template in ppt, if the template a designed ppt B and ppt c,ppt B and ppt C public part is the template A, if their public parts need to change, then only need to change the template A can be, do not need to re-ppt B and ppt C changes. and radiation design, such as an elevator are installed some kind of alarm, once to update the alarm, you must update all. That is, for an abstract class, if you need to add a new method, you can directly add a concrete implementation in the abstract class, the subclass can not be changed, but for the interface is not, if the interface has been changed, all implementations of this interface must be modified by the corresponding class.

Here's an example of the most widely circulated online: doors and Alarms: doors have open () and close () two actions, at which point we can define this abstract concept through abstract classes and interfaces:

Abstract class Door {public    abstract void Open ();    public abstract void Close ();}

Or

Interface Door {public    abstract void Open ();    public abstract void Close ();}

But now if we need the door to have the function of alarm alarm (), then how to implement? Here are two ideas:

1) These three functions are placed in the abstract class, but so that all the subclass inherited from the abstract class has an alarm function, but some doors do not necessarily have the alarm function;

2) The three functions are placed in the interface, need to use the alarm function of the class need to implement the interface of open () and close (), perhaps this class does not have open () and close () these two functions, such as fire alarm.

As can be seen here, Door's open (), close () and alarm () are essentially two different categories of behavior, and open () and close () are intrinsic behavior characteristics of the gate itself, and alarm () is an extension of the additional behavior. So the best solution is to individually design the alarm as an interface that contains the alarm () behavior, door is designed as a separate abstract class that contains open and close two behaviors. Then design an alarm gate to inherit the door class and implement the alarm interface.

Interface Alram {    void alarm ();} abstract class Door {    void open ();    void close ();} Class Alarmdoor extends Door implements Alarm {    void Oepn () {      //...    }    void Close () {      //...    }    void Alarm () {      //...    }}


4. Summary

1. Abstract classes and interfaces cannot be instantiated directly, and if instantiated, the abstract class variable must point to the subclass object that implements all the abstract methods, and the interface variable must point to the class object that implements all the interface methods.

2, abstract class to Quilt class inheritance, interface to be class implementation.

3, interface can only do method declaration, abstract class can do method declaration, can also do method to achieve

4, the variables defined in the interface can only be public static constants, the variables in the abstract class are ordinary variables.

5. Abstract methods in abstract classes must all be implemented by the quilt class, if the subclass can not fully implement the parent class abstract method, then the subclass can only be abstract class. Similarly, when an interface is implemented, if the interface method cannot be fully implemented, then the class can only be an abstract class.

6, the abstract method can only affirm, cannot realize. abstract void ABC (); cannot be written as abstract void abc () {}.

7, abstract class can have no abstract method

8, if there is an abstract method in a class, then this class can only be abstract class

9, abstract methods to be implemented, so can not be static, nor can it be private.

10, the interface can inherit the interface, and can inherit the interface more, but the class can only inherit one root.

in particular, for the common implementation code, the abstract class has its advantages. Abstract classes can guarantee the hierarchical relationship of implementation and avoid duplication of code. However, even when using abstract classes, it is important not to overlook the principle of defining behavior models through interfaces. From a practical point of view, if you rely on abstract classes to define behavior, it often leads to overly complex inheritance relationships, and it is more efficient to separate behaviors and implementations through interface definition behavior, which facilitates the maintenance and modification of code.


Reference:

Http://www.cnblogs.com/vamei/archive/2013/03/31/2982240.html

Http://www.cnblogs.com/dolphin0520/p/3811437.html

Http://www.cnblogs.com/azai/archive/2009/11/10/1599584.html

Http://www.cnblogs.com/xdp-gacl/p/3651121.html

Http://www.cnblogs.com/vamei/archive/2013/03/27/2982230.html


interface and abstract class Java

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.