Java Fundamentals 13-Abstract classes, methods, and interfaces

Source: Internet
Author: User
Tags modifier

First, abstract class

1. What is an abstract class?

Let us first look at how Baidu explains:

Abstract classes are often used to characterize the abstract concepts of analysis and design of problem areas, and are abstractions of a series of concrete concepts that look different, but are essentially the same.

In fact, the class itself is an abstract concept, but it is a concrete thing, so it is called the concrete class, abstract class seems to be in itself we have common in the class of the further extraction division, further abstraction, so that it does not have the characteristics of the instantiated object, it is unable to initialize the class .

2. Why should there be abstract classes? What is the point of it?

Let's look at such a picture.

We can create a cat object, or we can create a dog object, but if we create a feline object or a canine object, what kind of animal should we create specifically?

Do you want to create a cat or a lion? Do you create a dog or do you create a wolf? A little bigger, if we create animal objects, that's all, so many animals, in the end is to create that? Is it difficult to create a hybrid species?

So, from here we may feel a little bit about the concept of abstract classes and why there are abstract classes, because whether it is a cat class or a canine class, it should not be possible to create objects, and they should not be initialized.

But we must have them to build the tree, to inherit and produce polymorphism, which embodies the Java object-oriented thinking, what should be done?

So we just have to limit them, only their subclasses, the specific class to create the object is not OK, this is the purpose of abstract classes, to prevent the creation of objects should not be created by the class object.

3. Definition of abstract classes and methods

abstract classes and methods with The abstract keyword to define.

The definition format is as follows:

Abstract class:

Abstract class class name {

}

Abstract method: Public abstract return value type method name (parameter);

 Public Abstract classEmployee {//Abstract keyword-decorated abstraction class    PrivateString name; Private intNumber ; PrivateString Job; Private Doublesalary; Private DoubleBounes;//abstract method, no method body!      Public Abstract voidWork ();  Public Abstract voidwelfare ();}

Attention:

① abstract methods must be written in abstract classes, but abstract classes do not necessarily write abstract methods.

② any subclass must override the parent class's abstract method, or declare itself an abstract class.

③ constructor methods, class methods (methods that are decorated with static) cannot be declared as abstract methods.

 Public Abstract classMaintaindepartmentextendsemployee{//This is a child abstract class of employeeString CheckIn;//you can override an abstract method in a parent class as an implementation class     Public voidWork () {System.out.println ("Maintenance work"); }     Public voidWelfare () {System.out.println ("The Cat."); }//It is also possible to implement this method by Maintaindepartment subclasses without overriding the abstract method .     Public Abstract voidskill ();}

4. Meaning and benefits of abstract methods

The significance of the abstract method is that we put the inheritable method body in the parent class, but the parent class has no way to make any subclass meaningful common program code, when we use abstract methods, even if the content of the method can not be implemented, or we could define a seed class common protocol.

The advantage of abstract methods is polymorphism. We can add new subclasses to the program, and we don't have to rewrite or modify the programs that handle these types.

Second, the interface

1. What is an interface?

Interface (English: Interface), which is an abstract type in the Java programming language, is a collection of abstract methods, and interfaces are usually declared with Interface. A class inherits the abstract method of an interface by inheriting the interface.

The interface only describes the methods that should be available, and there is no specific implementation, the implementation of the interface is implemented by the class (equivalent to the subclass of the interface) to complete. This separates the definition and implementation of the function and optimizes the program design.

For example: The computer's power plug is an interface, it is to achieve the function of charging, so we do not have to care how to charge the (current, voltage ...) ), the function of charging can be realized as long as the power cord is plugged into this interface.

2. Why should I have an interface?

First of all, the class can only inherit, because multiple inheritance may have a " fatal block (shape looks like a poker box)" Problem

Therefore, in order to solve the problem of multiple inheritance, and do not produce a fatal block problem , the interface is gorgeous in our stage.

How does the interface solve the problem?

It sets all the methods to be abstract! This way the class has to implement this method, so the virtual machine will not be able to understand which inherited version to use when executing.

3. Definition of the interface

An interface definition is required to use the Interface key word.

Note: The definition of the interface is still a. Java file, although the declaration uses the interface keyword after compilation will still produce the. Class file . This allows us to consider an interface as a special class that contains only functional declarations.

Public interface Interface name {

abstract method 1;

abstract method 2;

abstract method 3;

}

 Public Interface Highpoint {publicvoid  Autopark ();  Public void AutoRun ();}

4. Class implementation Interface

The relationship of a class to an interface is to implement the relationship, that is, the class implements the interface. The implemented action is similar to inheritance, except that the keywords are different and implemented using implements.

After the class implements the interface, the class inherits the abstract method from the interface, and the class needs to override the abstract method to complete the specific logic.

 Public class extends Implements iplay{    publicvoid call () {        System.out.println ("Keyboard");    }      Public void SendMessage () {        System.out.println ("key");    }      Public void PlayGame () {        System.out.println ("King Glory");}    }

5. Similarities and differences between interfaces and abstract classes

Same point :

    • are located at the top of the inheritance for implementation or inheritance by other classes;
    • can not instantiate objects directly ;
    • all contain abstract methods , and their subclasses must overwrite these abstract methods;

difference :

    • abstract classes provide implementations for some of the methods, which prevent subclasses from repeating these methods and improve code reuse; Interfaces can contain only abstract methods;
    • A class can inherit only one direct parent class (possibly abstract class), but can implement multiple interfaces; (interface compensates for Java's single inheritance)
    • Abstract class is what you should have in this thing, the inheritance system is an IS. A relationship
    • Interface is the extra content of this thing, the inheritance system is a like. A relationship

the choice of the two:

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

Abstract classes are required to define the behavior of subclasses and to provide common functionality for subclasses.

6. Member features of the interface

    • The variable can be defined in the interface, but the variable must be decorated with a fixed modifier, Public static Final so the variable in the interface is also called a constant, and its value cannot be changed. We'll explain the static and final keywords later
    • The method can be defined in the interface, and the method has a fixed modifier, Public Abstract
    • The interface is not available to create objects.
    • Subclasses must overwrite all the abstract methods in the interface before the subclass can instantiate. Otherwise, the subclass is an abstract class.

Java Fundamentals 13-Abstract classes, methods, and interfaces

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.