Java learning abstract classes and interfaces

Abstract class

When a class is decorated with abstract, this class is an abstract class; the method decorated with abstract is called an abstract method. Here are a few points to note:
1. The class containing abstract methods must be declared as abstract classes (interfaces are deep abstractions of abstract classes), abstract classes must be inherited (otherwise they are meaningless), and abstract methods must be rewritten.
2. The abstract method only needs to be declared, not implemented.
3. Abstract classes cannot be instantiated, because most abstract classes have abstract methods, abstract methods have no method body, and instantiation will report an error. In addition, there can also be some abstract classes without abstract methods, but there is no difference between classes without abstract methods and entity classes, so abstract classes without abstract methods are meaningless.
3. Abstract classes can contain entity methods or member variables.

The following is an example of the grammatical structure:

abstract class Animal{
    
    
    //抽象类可以具有实体方法和成员变量
    private String name;
    Animal(String name){
        this.name=name;
    }
    //抽象方法,权限只能是public或者protected
    public abstract void enjoy();
}

class Cat extends Animal{
    
    
    private String eyesColor;
    Cat(String n,String c){
        //调用父类构造函数
        super(n);
        eyesColor=c;
    }
    //重写抽象方法
    public void enjoy(){
        System.out.println("猫叫声....");
    }
}

In fact, it can be seen from the above example that the abstract methods of abstract classes are designed to be rewritten by others to achieve object-oriented polymorphism. If the subclass does not want to implement abstract methods, then the subclass must also add the keyword abstract to declare the subclass as an abstract class.

interface

Use interface to define an interface. Interface definition is similar to class definition, divided into interface declaration and interface body. The interface body is composed of two parts: constant definition and method definition. Pay attention to the use of interfaces:
1. Interfaces can contain constants (note that they are not variables) and methods, and the constants in the interface will be implicitly designated as public static final (this can also explain why they are constants and cannot exist variables), Will be implicitly designated as a public abstract method. You can check the link for specific reasons: Why are interface variables public static final by default?
2. Interface is a deeply abstract type.
3. The interface does not have any implementation and is most suitable as a base class.

The basic format for defining the interface is as follows:

 [修饰符] interface 接口名 [extends 父接口名列表]{
    
    
    //可选参数public,如果省略,则为默认的访问权限;
     [public] [static] [final] 常量;
     [public] [abstract] 方法;
 }

To implement the interface, use the implements keyword:

[修饰符] class <类名> [extends 父类名] [implements 接口列表]{
    
    
    //重写接口方法
    ...
}

Here is an example:

//定义各功能接口
interface CanFight {
    
    void fight();}
interface CanFly {
    
    void fly();}
interface CanSwim {
    
    void swim();}
//定义一个抽象
class ActionCharacter {
    
    public void fight(){}}
class Hero extends ActionCharacter implements CanFight, CanFly, CanSwim {
    
    

    @Override
    public void swim() {}

    @Override
    public void fly() { }

}
public class Adventure {
    
    

    public static void t(CanFight x){x.fight();}

    public static void u(CanSwim x){x.swim();}

    public static void v(CanFly x){x.fly();}

    public static void w(ActionCharacter x){x.fight();}

    public static void main(String[] args) {
        Hero h = new Hero();
        t(h);
        u(h);
        v(h);
        w(h);
    }
}

From the example we can see:
1. Hero has the functions of each interface at the same time
2. Hero can be converted to these interfaces implemented by it. When we pass the hero object as a parameter to each method of the Adventure class, Hero The class has been transformed upwards. It can be seen that the benefits of the interface can achieve upward transformation, and multiple classes with common attributes can extract their common points and make them abstract, so that the hierarchy is clear and unified management.

Here is an additional point of knowledge: upward transformation is transferable . For example, if the subtype of A is B and the subtype of B is C, then the following statement

A a0=new A();
A a1=new B();
A a2=new C();

All meet the conditions correctly.

The difference and relationship between interface and abstract class

relationship

Realize and improve Java's multiple inheritance functions by combining interfaces and abstract classes.

the difference

  1. Abstract classes are classes and can have entity methods.
  2. Abstract classes cannot implement multiple inheritance, while interfaces can.
  3. If you need to create a base class without any method definitions and member variables, use an interface. If the class requires some concrete implementation, use an abstract class.
  4. If you want to design a class as a base class in advance, then the interface is preferred. == (Note that c and d are the usage scenarios of the interface) ==
  5. An abstract class is an abstraction of a kind of thing, that is, an abstraction of a class, and an interface is more an abstraction of behavior.

An example of a door and an alarm is circulating on the Internet: the door has two actions: open() and close( ). At this time, 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 an alarm () function, then how to achieve it? Two ideas are provided below:

1) Put these three functions in the abstract class, but in this way all subclasses inherited from this abstract class have the alarm function, but some doors may not have the alarm function;

2) Put these three functions in the interface, the class that needs the alarm function needs to implement the open() and close() in this interface, maybe this class does not have open() and close() at all Two functions, such as fire alarm.

It can be seen from this that the door's open(), close() and alarm() basically belong to two different categories of behavior, open() and close() belong to the inherent behavior characteristics of the door itself, and alarm() belongs to Extended additional behavior. Therefore, the best solution is to design the alarm as an interface, including the alarm() behavior, and the Door as a separate abstract class, including the two behaviors of open and close. Then design an alarm door 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() {
      //....
    }
}

Reference materials:

https://www.cnblogs.com/xdp-gacl/p/3648398.html
https://blog.csdn.net/zhangerqing/article/details/8298603

Guess you like

Origin blog.csdn.net/dypnlw/article/details/82656138