The differences between abstract classes and interfaces in Java

Source: Internet
Author: User
Tags define abstract extend

In the Java Foundation, often encounter about the interface and abstract class related to the description and problems, and then I searched on Baidu A lot of relevant answers, are very messy, are directly introduced 2 of the difference, no introduction 2 reasons, and a lot of information is the same; if you haven't touched the basics for a long time, it seems hard to understand Rise up today, write the difference between the two.

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------

1. Abstract class 1.1. Generation of abstract classes

When writing a class, we tend to define methods for the class that describe how the class behaves, and these methods have a concrete method body. Sometimes, however, a parent class just knows what the subclass should contain, but it doesn't know exactly how the subclass implements the methods. For example, a graphics class should have a method of finding the perimeter, but different graphs for the perimeter of the algorithm is not the same. What should we do then?

When we analyze things, we find common content, and then we extract them upwards. There is a special case where the function declarations are the same, but the functional bodies are different. Then it can be extracted, but only the method declaration is extracted, and the method body is not extracted. Then this method is an abstract method.

Description Dog: Behavior: Roar.

Description Wolf: Behavior: Roar.

There is a common denominator between the dog and the wolf, which can be extracted upward. Extract their generic type: Canine section. Dogs and wolves have a roaring function, but they are different in how they roar. At this time in the description of the canine branch, found that some functions (growl) is not specific, these non-specific functions, need to be identified in the class, through the Java keyword Abstract (abstract).

Classes that define abstract functions must also be decorated with the abstract keyword, and the class that is decorated by the abstract keyword is an abstract class.

1 Abstract classCanine Department2 {3     Abstract voidRoar ();//abstract function. Requires an abstract modifier, and a semicolon;4 }5 classDogextendsCanine Department6 {7     voidRoar ()8     {9System.out.println ("Barking");Ten     } One } A classWolfextendsCanine Department - { -     voidRoar () the     { -System.out.println ("Whining whining"); -     } -}
1.2. Characteristics of abstract Classes

1. Abstract classes and abstract methods need to be modified by abstractions. Abstract methods must be defined in an abstract class.

2. Abstract class cannot create an instance because it is meaningless to invoke an abstract method.

3, only after overriding all abstract methods in the abstract class, its subclasses can be instantiated. Otherwise, the subclass is an abstract class.

Inheritance, more in the mind, is to face the common type of operation will be more simple.

1.3. Details of the abstract class

1, abstract class must be a parent class?

Yes, because of the constant extraction.

2. Does the abstract class have a constructor function?

Yes, although you cannot initialize your own objects, you can initialize your own subclass objects.

The similarities and differences between abstract classes and general classes:

Same:

1, they are used to describe things.

2. You can define attributes and behaviors among them.

Different:

1, the general class can describe things concretely. Abstract class describes the information of a thing is not specific

2. You can define more than one member in an abstract class: an abstract function.

3. Generic classes can create objects, and abstract classes cannot create objects.

3. Whether abstract methods can be undefined in an abstract class.

Yes, what is the meaning of the existence of this abstract class? Just don't let the class create objects.

4. Abstract keywords can not and which keywords to coexist?

    • FINAL:FIANL-Modified classes cannot be inherited, and abstract-decorated classes must have subclasses. The final modified method cannot be overridden, but the method of the abstract modification must be implemented by the quilt class.
    • Static: The statically decorated method belongs to the class, it exists with the static zone, and the object does not matter. There is no method body for an abstract method, and calling it with a class name has no meaning.
    • Private: The method subclass is not inherited, and there is no overwrite, and abstract and private use the adornment method, abstract both subclass to implement this method, and private modifier subclass can not get the parent class this method. Contradict each other.
2. Interface 2.1. Definition and implementation of interface

When all the methods in an abstract class are abstract, then this abstract class can be represented by the mechanism of another interface.

How does the interface define it? Defining an ordinary class or abstract class can use the Class keyword, which defines that the interface must interface the keyword.

Interface class demo{    abstractvoid  show1 ();     Abstract void show2 ();}

Features of the members in the interface:

1, the interface can be defined variables, but the variable must have a fixed modifier decoration, public static final so the variable in the interface is also called a constant.

2, the interface can be defined methods, methods also have fixed modifiers, public abstract

3, the members of the interface are public.

4. Interfaces are not available to create objects.

5, subclasses must overwrite all the abstract methods in the interface, subclasses can be instantiated. Otherwise, the subclass is an abstract class.

InterfaceDemo//defines an interface named demo. {     Public Static Final intNUM = 3;  Public Abstract voidShow1 ();  Public Abstract voidshow2 ();}//define subclasses to override methods in the interface. A subclass must have a relationship with an interface, a class-to-class relationship is an inheritance, and a relationship between a class and an interface is an implementation. by keyword implementsclassDemoimplImplementsDemo//sub-class implementation of the demo interface. {    //overrides the method in the interface.      Public voidShow1 () {} Public voidShow2 () {}}
2.2. Multiple implementations of interfaces

Understanding the characteristics of the interface, then think about why to define the interface, the use of abstract class description is no problem, the interface exactly what is the use of it?

Interface The most important embodiment: to solve the disadvantages of multiple inheritance. This mechanism of multi-inheritance is done in Java through multiple implementations.

Interface a{    void  show1 ();} Interface b{    void  show2 ();} class Implements A, B//  multiple implementations. Implement multiple interfaces at the same time.  {    publicvoid  Show1 () {}    publicvoid  Show2 () {}}

How to solve the disadvantages of multiple inheritance? ()

Cons: When multiple inheritance occurs, when multiple parents have the same functionality, the subclass invocation creates uncertainty.

In fact, the core reason is that multiple inheritance of the function in the parent class has a principal, which causes the call runtime to not determine which principal content to run.

Why is it solved by multiple implementations?

Because the functionality in the interface has no method body, it is explicit by subclasses.

2.3. Class-Inheriting classes implement interfaces at the same time

Interfaces and classes can be implemented in relation to each other, as well as learning about the relationships between classes and classes that can be inherited. When describing things, if this thing is already one of the whole system of things, it needs to extend the additional function, then the interface comes into use.

Subclasses extend functionality by inheriting the parent class, and the functionality that is extended through inheritance is the underlying functionality that subclasses should have. What if subclasses want to continue extending functionality in other classes? This is done by implementing an interface.

class fu{    publicvoid  Show () {}}interface  inter{    void  Show1 ();} class extends Implements inter{    publicvoid  Show1 ()    {            }}

The presence of interfaces avoids the limitations of single inheritance. The basic functionality of the things defined in the parent class. The extended functionality of the things defined in the interface.

2.4. Multiple inheritance of interfaces

When you learn a class, you know that the relationship between the class and the class can be inherited, and the interface and the class can relate to each other through the implementation, then what is the relationship between the interface and the interface.

You can use extends to inherit between multiple interfaces.

Interface a{    void  Show (); Interface b{    void  show1 ();} Interface c{    void  show2 ();} Interface extends a,b,c{    void  show3 ();}

In the development if there are multiple interfaces in the same way, then if there is a class implementation of these interfaces, then the implementation of the interface method, because the interface method is an abstract method, the sub-class implementation will not occur after the call of uncertainty.

2.5. The idea of the interface

For Example: We all know that there are many sockets on the computer, and these sockets can be plugged into the appropriate devices, why can they be plugged in? The main reason is that these devices conform to the usage rules of the socket when they are produced, otherwise they will not be able to be plugged into the interface or be unusable. Discover the presence of this socket and let us use more devices.

Summary: interface in the development of its benefits

1, the appearance of the interface expands the function.

2, the interface is actually leaking out of the rules.

3, the appearance of the interface reduces the coupling, that is, the realization of decoupling between equipment and equipment.

The appearance of the interface is convenient for later use and maintenance, one side is in the use of the interface (such as computer), a party in the implementation of the interface (plugged in the device). For example: Notebooks Use this rule (interface), computer peripherals implement this rule (interface).

3. The difference between an interface and an abstract class

What is the difference between an interface and an abstract class when you understand the use of interface ideas and interfaces? Interface in the life embodiment also basic grasp, that in the program interface is how to embody?

Examples are used to analyze and code to demonstrate the use of abstract classes and interfaces.

1. For example:

Dog:

Behavior:

Roar

Eat

Drug Dog:

Behavior:

Roar

Eat

Drug

2, thinking:

Because dogs are divided into many kinds, they roar and eat different ways, in the description of the time can not be specific, that is, the behavior of shouting and eating can not be clear, describing the behavior, the behavior of the specific action can not be clear, the behavior may be written as abstract behavior, then this class is abstract class. But when the dog has other extra functions, this function is not in the system of this thing. This allows the dog to have its own characteristics and other additional functions, which can be defined in an interface.

InterfaceAnti- Narcotics {voidDrug Enforcement ();}//define the general function of this extraction in canineAbstract classCanine Branch {Abstract voideat (); Abstract voidroar ();}//a drug dog belongs to a canine family, allowing it to inherit from the canine family, to obtain the characteristics of the canine family,//because the drug-suppressing dog has the anti-drug function, then it can only realize the drug interface, so that the drug dog has the characteristics of canine, but also has the function of anti-narcoticsclassDrug dogsextendsCanine DepartmentImplementsAnti- Narcotics { Public voidAnti -Narcotics () {}voideat () {}voidroar () {}}classDrug pigsImplementsAnti- Narcotics { Public voidAnti -Narcotics () {}}

3, through the above example summarizes the interface and abstract class difference: ★★★★★

Same point:

are located at the top of the inheritance and are used for other implementations or inheritance;

Can not be instantiated;

All contain abstract methods, and their subclasses must overwrite these abstract methods;

Difference:

Abstract classes provide implementations for partial methods, which prevent subclasses from repeatedly implementing these methods, providing code reuse, and interfaces containing only abstract methods;

A class can inherit only one direct parent class (possibly an abstract class), but may implement multiple interfaces; (interface compensates for Java's single inheritance)

The choice of the two:

Preferential selection of interface, as far as possible to use abstract classes;

Abstract classes are used to define the behavior of subclasses and to provide common functions for subclasses.

The differences between abstract classes and interfaces in 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.