Boring JavaEE from entry to abandonment (10) abstract method_abstract class & interface

table of Contents

One.abstract

1. Abstract method

2. Abstract class

3. The main points of the use of abstract classes

4. Sample code

2. Interface

1. What is the interface

2. The role of the interface

3. Difference

4. Format

(1) Declaration format:

(2) A detailed description of the defined interface

(3) Key points

5. Sample code

6. New features of the interface after JDK8

(1) Default method

(2) Static method


One.abstract

1. Abstract method

Using abstract modified methods, there is no method body, only declarations. What is defined is a "norm", which tells subclasses that they must provide concrete implementations for abstract methods.

2. Abstract class

A class that contains abstract methods is an abstract class. Define the specification through the abstract method, and then require that the subclass must define a specific implementation.

Through abstract classes, we can strictly limit the design of subclasses and make the subclasses more versatile.

3. The main points of the use of abstract classes

(1) A class with abstract methods can only be defined as an abstract class
(2) An abstract class cannot be instantiated, that is, an abstract class cannot be instantiated with new.
(3) Abstract classes can contain attributes, methods, and construction methods. But the constructor cannot be used for new instances, it can only be used by subclasses.
(4) Abstract classes can only be used to be inherited.
(5) Abstract methods must be implemented by subclasses.

4. Sample code

public abstract class Student {
    private String name;

    abstract public void study();
    abstract public void exam();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    //以后如果是父类,那么不管三七二十一,都要加上无参构造器
    Student(){

    }
}
class Test{
    public static void main(String[] args) {
        //Student stu=new Student();抽象类不能创建对象
        Student stu=new SxtStu();
        stu.study();
        stu.exam();
    }
}

class SxtStu extends Student{

    @Override
    public void study() {
        System.out.println("好好学习,好好谈恋爱,好好敲代码!");
    }

    @Override
    public void exam() {
        System.out.println("考个100分!");
    }
}

Output:

好好学习,好好谈恋爱,好好敲代码!
考个100分!

2. Interface

1. What is the interface

The interface is the specification, which defines a set of rules , which embodies the real world's "if you are... you must be able to...". If you are an angel, you must be able to fly. If you are a car, you must be able to run. If you are a good person, you must be able to kill the bad person; if you are a bad person, you must bully others.
The essence of the interface is a contract, just like our human law. After it is formulated, everyone will abide by it.
The essence of object-oriented is right The abstraction of objects can best reflect this point is the interface.

Why we discuss design patterns are only for languages ​​with abstraction capabilities (such as C++, Java, C#, etc.), because the design patterns studied are actually how to abstract reasonably.

2. The role of the interface

Why do I need an interface? The difference between an interface and an abstract class? An
interface is an "abstract class" that is more "abstract" than an "abstract class", and can restrict subclasses more normatively. Realized comprehensively and professionally: the separation of norms and concrete realizations.
Abstract classes also provide some concrete implementations, interfaces do not provide any implementations, and all methods in the interface are abstract methods. The interface is completely specification-oriented and specifies the public method specifications of a batch of classes.
From the perspective of the implementer of the interface, the interface defines the services that can be provided to the outside.
From the perspective of the caller of the interface, the interface defines the services that the implementer can provide.
The interface is the standard of communication between two modules, and the norm of communication. If you can define the interface between the modules you want to design, it is equivalent to completing the system design outline, and the rest is the concrete realization of adding bricks and tiles. After you work, you often use the "interface-oriented" thinking to design the system when you build the system. Interfaces and implementation classes are not a parent-child relationship, but a relationship that implements rules. For example: I define an interface Runnable, Car implements it to run on the ground, Train implements it can also run on the ground, and airplane implements it can also run on the ground. That is to say, if it is a vehicle, it will be able to run, but it must implement the Runnable interface.

3. Difference

Ordinary class: concrete implementation
Abstract class: concrete implementation, specification (abstract method)
Interface: specification! (Before jdk8, there were only specifications, and static methods and default methods were added after jdk8)

4. Format

(1) Declaration format:

[Access modifier] interface interface name [extends parent interface 1, parent interface 2..] {                         constant definition;                         method definition; }


(2) A detailed description of the defined interface

Access modifier: can only be public or default.
Interface name: Use the same naming mechanism as the class name.
extends: The interface can be inherited multiple times.

The interface fully supports multiple inheritance. Similar to class inheritance, a child interface extends a parent interface and will get everything defined in the parent interface.

Constants: The attributes in the interface can only be constants, always: public static final modification. Even without writing.
Method: The method in the interface can only be: public abstract if omitted, it is also public abstract.

(3) Key points

Subclasses implement the specifications in the interface through implements.
Interfaces cannot create instances, but can be used to declare reference variable types .
A class implements an interface, it must implement all the methods in the interface, and these methods can only be public.
Before JDK1.8 (excluding 8), the interface can only contain static constants and abstract methods, and cannot have ordinary attributes, construction methods, and ordinary methods.
After JDK1.8 (including 8), the interface contains ordinary static methods and default methods.

5. Sample code

(File structure)

Pilot interface:

/**
 * 这是一个飞行器接口
 */
public interface Pilot {
    /**
     * 表示飞行器在地球这个星球上飞的最高的高度,单位是:公里
     */
    /*public static final*/ int MAX_HEIGHT=100;

    /**
     * 飞行方法,飞行器可以起飞
     */
    /*public abstract*/ void fly();

    /**
     * 可以让飞行器停止,如果在空中就是悬停,如果在地上就是静止
     */
    void stop();
}

interface Honest{
    void helpOther();
}
SuperMan类
public class SuperMan implements Pilot,Honest{接口是可多继承的
    //Alt+Enter智能补全需要实现的方法
    @Override
    public void fly() {
        System.out.println("横着飞!");
    }

    @Override
    public void stop() {
        System.out.println("竖着停!");
    }

    @Override
    public void helpOther() {
        System.out.println("哪里call我,飞哪里!");
    }

    public static void main(String[] args) {
        /*
        SuperMan m1=new SuperMan();
        m1.fly();
        m1.helpOther();
         */
        Pilot p1=new SuperMan();//编译器就认为对象p1是Pilot型的,但是调用方法时还是new的对象的方法
        p1.fly();
        //因为编译器就认为对象p1是Pilot型的,所以想执行helpOther()函数还需要强制类型转换!
        Honest h=(Honest)p1;
        h.helpOther();
    }
}

Output:

横着飞!
哪里call我,飞哪里!

6. New features of the interface after JDK8

Before JAVA8, all the methods in the interface are required to be abstract methods.
After JAVA8 (including 8), it is allowed to define default methods and class methods in interfaces in the future.

(1) Default method

Java 8 and above old versions allow to add a non-abstract method implementation to the interface. You only need to use the default keyword. This feature is also called the default method (also called an extension method).
The difference between the default method and the abstract method is that the abstract method must be implemented, the default method is not. As an alternative, the interface can provide the implementation of the default method, and all implementation classes of this interface will get this method through inheritance.

public class Test {
    public static void main(String[] args) {
        A a=new Test_A();
        a.moren();//默认方法通过实现类的对象来调用
    }

}
class Test_A implements A{
    @Override
    public void moren() {
        System.out.println("Test_A moren");
    }
}
interface A{
    default void moren(){
        System.out.println("我是接口A中的默认方法!");
    }
}

(2) Static method

After JAVA8, we can also directly define the implementation of static methods in the interface. This static method is directly subordinate to the interface (the interface is also a class, a special class) and can be called by the interface name.
If a static method with the same name is defined in a subclass, it is a completely different method and directly subordinate to the subclass. It can be called directly by the subclass name.

Sample code:

public class Test1 {
    public static void main(String[] args) {
        A1.staticMethod();//静态方法可直接用类名调用
        Testt_A1.staticMethod();
    }
}

interface A1{
    public static void staticMethod(){
        System.out.println("A1.staticMethod");
    }
}

class Testt_A1 implements A{
    public static void staticMethod(){
        System.out.println("Testt_A1.staticMethod");
    }
}

Output:

A1.staticMethod
Testt_A1.staticMethod

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_44593822/article/details/115369364