JavaSE--Abstract classes and interfaces

Table of contents

Preface

1.Abstract class

1.1 Concept of abstract class

1.2 Abstract class syntax

1.3 Abstract class characteristics

1.4 The role of abstract classes

2. Interface 

2.1 Concept of interface

2.2 Grammar rules

2.3 Interface usage

2.4 Interface characteristics

2.5 Implement multiple interfaces 

2.6 Inheritance between interfaces

2.7 The difference between abstract classes and interfaces (common interview questions)

Summarize



Preface

With an in-depth understanding of inheritance and polymorphism in Java, this article will introduce new content: abstract classes and interfaces.


1.Abstract class

1.1 Concept of abstract class

In the object-oriented concept, all objects are described by classes, but conversely, not all classes are used to describe objects. If a class does not contain enough information to describe a specific object , such a class is an abstract class .

for example:

 

 Through the above examples, we can find that the draw() method in Shape and the bark() method in Animal do not have any actual work. The main work is completed by subclass inheritance. For methods like this that have no actual work, we can design them as abstract methods . The class containing the abstract method is called an abstract class.

1.2 Abstract class syntax

In Java, if a class is modified by abstract , it is called an abstract class. The method in the abstract class that is modified by abstract is called an abstract method. Abstract methods do not need to give a specific implementation body.

// 抽象类:被abstract修饰的类
public abstract class Shape {
    // 抽象方法:被abstract修饰的方法,没有方法体
    public abstract void draw();
    abstract void calcArea();
    // 抽象类也是类,也可以增加普通方法和属性
    public double getArea(){
        return area;
    }
    protected double area; // 面积

 Note: Abstract classes are also classes, which can contain ordinary methods, properties, and even constructors!

1.3 Abstract class characteristics

1. Abstract classes cannot directly instantiate objects.

Shape shape = new Shape();
// 编译出错
Error:(30, 23) java: Shape是抽象的; 无法实例化

 2. Abstract methods cannot be private

abstract class Shape {
    private abstract void draw();
} 
// 编译出错
Error:(4, 27) java: 非法的修饰符组合: abstract和private

 Abstract methods must be overridden, so they must not be modified by private

3. Abstract methods cannot be modified by final and static, because abstract methods must be overridden by subclasses

public abstract class Shape {
    abstract final void methodA();
    public abstract static void methodB();
}
// 编译报错:
// Error:(20, 25) java: 非法的修饰符组合: abstract和final
// Error:(21, 33) java: 非法的修饰符组合: abstract和static

4. Abstract classes must be inherited, and after inheritance, the subclass must override the abstract method in the parent class. Otherwise, the subclass is also an abstract class and must be modified with abstract.

class Cycle extends Shape{
    @Override
    public void draw() {
        //这里对Shape类中的两个抽象方法进行了重写,就不会报错
    }
    @Override
    void calcArea() {

    }
}

If all rewriting is not completed, modifying this class with abstract will not cause an error.

abstract class Cycle extends Shape{
    @Override
    void calcArea() {

    }
}

If all rewriting is not completed and abstract modification is not used, an error will definitely be reported!

5. An abstract class does not necessarily contain abstract methods, but a class with abstract methods must be an abstract class.
6. An abstract class can have a constructor method for the subclass to initialize the member variables of the parent class when creating an object.

1.4 The role of abstract classes

The abstract class itself cannot be instantiated. To use it, you can only create a subclass of the abstract class. Then let the subclass override the abstract method in the abstract class.

A question may arise here: Ordinary classes can also be inherited, and ordinary methods can also be overridden. Why do we have to use abstract classes and abstract methods?

The scenario of using an abstract class is like the above code. The actual work should not be done by the parent class, but by the subclass. If you accidentally misuse it as a parent class at this time, you will not get an error using the ordinary class compiler. .But if the parent class is an abstract class, an error will be prompted during instantiation . Let us find the problem as early as possible.

The purpose of many syntaxes is to "prevent errors." For example, the final we have used is similar. If the created variable is not modified by the user, isn't it equivalent to a constant? But adding final can prevent it from being accidentally modified. , let the compiler remind us in time. Making full use of the compiler's verification is very meaningful in actual development.


2. Interface 

2.1 Concept of interface

In real life, examples of interfaces abound, such as USB ports on laptops, power sockets, etc.

 

The USB port of the computer can be plugged into: U disk, mouse, keyboard...all devices that comply with the USB protocol. The
power outlet jack can be plugged into: computer, TV, rice cooker...all the equipment that meets the specifications
can be plugged into the above example. It can be seen that interfaces are public behavioral standards. When everyone implements them, as long as they comply with the standards, they can be used universally.
In Java, an interface can be thought of as: a common specification for multiple classes, which is a reference data type.

2.2 Grammar rules

The definition format of the interface is basically the same as the format of defining the class. Replace the class keyword with the interface keyword to define an interface.

public interface 接口名称{
    // 抽象方法
    public abstract void method1(); // public abstract 是固定搭配,可以不写
    public void method2();
    abstract void method3();
    void method4();
// 注意:在接口中上述写法都是抽象方法,跟推荐方式4,代码更简洁
}

2.3 Interface usage

The interface cannot be used directly. There must be an "implementation class" to "implement" the interface and implement all abstract methods in the interface.

public class 类名称 implements 接口名称{
    // ...
}

Note: The inheritance relationship between subclasses and parent classes is extends, and the implementation relationship between classes and interfaces is implements. 

Next, write a case to understand the use of the interface

interface USB {
    void openService();
    void closeService();
}

public class Mouse implements USB{
    @Override
    public void openService() {
        System.out.println("打开鼠标");
    }

    @Override
    public void closeService() {
        System.out.println("关闭鼠标");
    }
    public void click(){
        System.out.println("点击鼠标");
    }
}

public class KeyBoard implements USB{

    @Override
    public void openService() {
        System.out.println("打开键盘");
    }

    @Override
    public void closeService() {
        System.out.println("关闭键盘");
    }
    public void input(){
        System.out.println("键盘输入");
    }
}


public class Computer {
    public void powerOn(){
        System.out.println("打开电脑");
    }
    public void powerOff(){
        System.out.println("关闭电脑");
    }

    /**
     * 这里利用多态
     * @param usb
     */
    public void useDevice(USB usb){
        usb.openService();
        //由于多态缺点:不能调用子类特有方法,只能向下转型
        if(usb instanceof Mouse){
            Mouse mouse = (Mouse)usb;
            mouse.click();
        }else if(usb instanceof KeyBoard){
            KeyBoard keyboard = (KeyBoard) usb;
            keyboard.input();
        }
        usb.closeService();
    }

}


public class Test {
    public static void main(String[] args) {
        Computer computer = new Computer();
        //先打开电脑
        computer.powerOn();
        //使用电脑的鼠标
        computer.useDevice(new Mouse());
        System.out.println("=============");
        //使用电脑的键盘
        computer.useDevice(new KeyBoard());
        //关闭电脑
        computer.powerOff();
    }
}

运行结果:
打开电脑
打开鼠标
点击鼠标
关闭鼠标
=============
打开键盘
键盘输入
关闭键盘
关闭电脑

 2.4 Interface characteristics

1. The interface type is a reference type, but the object of the new interface cannot be directly new.

public class TestUSB {
    public static void main(String[] args) {
    USB usb = new USB();
}
} 
// Error:(10, 19) java: day20210915.USB是抽象的; 无法实例化

 2. Every method in the interface is a public abstract method, that is, the methods in the interface will be implicitly designated as public abstract (it can only be public abstract, other modifiers will report an error )

public interface USB {
    // Error:(4, 18) java: 此处不允许使用修饰符private
    private void openDevice();
    void closeDevice();
}

3. The methods in the interface cannot be implemented in the interface, but can only be implemented by the class that implements the interface.

public interface USB {
    void openDevice();
    // 编译失败:因为接口中的方式默认为抽象方法
    // Error:(5, 23) java: 接口抽象方法不能带有主体
    void closeDevice(){
        System.out.println("关闭USB设备");
    }
}

4. When overriding methods in the interface, the default access permissions cannot be used

public class Mouse implements USB {
    @Override
    void openDevice() {//这里必须为public
        System.out.println("打开鼠标");
    } 
// ...
} 
// 编译报错,重写USB中openDevice方法时,不
// 正在尝试分配更低的访问权限; 以前为public

5. The interface can contain variables, but the variables in the interface will be implicitly designated as public static final variables.

public interface USB {
    double brand = 3.0; // 默认被:final public static修饰
    void openDevice();
    void closeDevice();
}
public class TestUSB {
    public static void main(String[] args) {
        System.out.println(USB.brand); // 可以直接通过接口名访问,说明是静态的
        // 编译报错:Error:(12, 12) java: 无法为最终变量brand分配值
        USB.brand = 2.0; // 说明brand具有final属性
    }
}

 6. There cannot be static code blocks and constructors in the interface

public interface USB {
    // 编译失败 //构造方法
    public USB(){

    }
    static{} // 编译失败//静态代码块
    void openDevice();
    void closeDevice();
}

7. Although the interface is not a class, the suffix format of the bytecode file after the interface is compiled is also .class
8. If the class does not implement all the abstract methods in the interface, the class must be set as an abstract class
9. In jdk8: Interface You can also include default methods.

public interface USB {
    public static void a(){
        //接口中的静态方法是被允许的
    }
    default void b(){
        //jdk8中支持default方法
    }
    void openDevice();
    void closeDevice();
}

2.5 Implement multiple interfaces 

In Java, there is single inheritance between classes. A class can only have one parent class. That is, multiple inheritance is not supported in Java, but a class can implement multiple interfaces. The following uses classes to represent a group of animals.
 

public class Animal {
    protected String name;
    public Animal(String name) {
        this.name = name;
    }
}

public interface IRunning {
    void run();
}

public interface ISwimming {
    void swim();
}

public class Cat extends Animal implements IRunning{
    public Cat(String name){
        super(name);
    }
    @Override
    public void run() {
        System.out.println(this.name+"正在用4条腿跑");
    }
}

public class Frog extends Animal implements IRunning,ISwimming{
    public Frog(String name){
        super(name);
    }
    @Override
    public void swim() {
        System.out.println(this.name+"正在蛙泳");
    }
    @Override
    public void run() {
        System.out.println("正在蛙跳");
    }
}

The above code shows the most common usage in Java object-oriented programming: a class inherits a parent class and implements multiple interfaces at the same time .

What are the benefits of this design? Always keep in mind the benefits of polymorphism and forget about types. With interfaces, users of classes do not have to pay attention to specific types, but only whether a certain class has certain capabilities.

For example, now implement the running method:

public static void Runs(IRunning running) {
    System.out.println("我带着伙伴去跑步");
    running.run();
}

 Inside this Runs method, we don’t care what kind of animal it is, as long as the parameters can run, that’s fine

public class Test {
    public static void Runs(IRunning running) {
        System.out.println("我带着伙伴去散步");
        running.run();
    }

    public static void main(String[] args) {
        Cat cat = new Cat("小猫");
        Runs(cat);
        Frog frog = new Frog("小青蛙");
        Runs(frog);
    }
}

运行结果:
我带着伙伴去散步
小猫正在用4条腿跑
我带着伙伴去散步
小青蛙正在蛙跳

 Even the parameter does not need to be an "animal", as long as it can run!

class Robot implements IRunning {
    private String name;
    public Robot(String name) {
        this.name = name;
    } 
    @Override
    public void run() {
        System.out.println(this.name + "正在用轮子跑");
    }
} 

public static void main(String[] args) {
    Robot robot = new Robot("机器人");
    Runs(robot);
}

// 执行结果
机器人正在用轮子跑

 Some people may ask, why not write these interfaces as abstract methods in the Animal class? Do you have to extract the interfaces one by one? This is because once written into the Animal class, this class is written to death. For example: not all animals can fly! But you still need to rewrite this method so that the coupling of the code is very high!

 

 2.6 Inheritance between interfaces

In Java, there is single inheritance between classes. A class can implement multiple interfaces, and interfaces can have multiple inheritance. That is: using interfaces can achieve the purpose of multiple inheritance.
An interface can inherit multiple interfaces to achieve reuse. Use the extends keyword.

interface IRunning {
    void run();
}

interface ISwimming {
    void swim();
} 

// 两栖的动物, 既能跑, 也能游
interface IAmphibious extends IRunning, ISwimming {

}
class Frog implements IAmphibious {
...
}

Creating a new interface IAmphibious through interface inheritance means "amphibious". At this time, the Frog class created to implement the interface continues to implement the run method and also needs to implement the swim method. Inheritance between interfaces is equivalent to merging multiple interfaces
together

2.7 The difference between abstract classes and interfaces (common interview questions)

The core difference: abstract classes can contain ordinary methods and ordinary fields. Such ordinary methods and fields can be used directly by subclasses (without rewriting), while interfaces cannot contain ordinary methods, and subclasses must rewrite all abstract methods.
Below Explain the difference between the two in detail:

  1.  Abstract classes can be modified by all permissions, interfaces can only be modified by public
  2.  Abstract classes can contain all keyword-modified member variables, and interfaces can only contain public final-modified member variables.
  3. Abstract classes can have abstract methods and ordinary methods. Interfaces can only be abstract methods and static methods modified by public abstract and default methods after jdk1.8.
  4. In abstract classes, subclasses use the extends keyword to inherit and use abstract methods, and in interfaces, subclasses use the implements keyword to implement the interface.
  5. Abstract classes can implement multiple interfaces, and interfaces cannot inherit. Abstract methods can only inherit interfaces and can inherit multiple interfaces.
  6. A subclass can only inherit one abstract class, but a subclass can implement multiple interfaces


Summarize

This article introduces abstract classes and interfaces in detail, and summarizes the difference between abstraction and interfaces (common interview test)

Guess you like

Origin blog.csdn.net/x2656271356/article/details/129725222