Home >Java >javaTutorial >How to implement interfaces and abstract classes in Java

How to implement interfaces and abstract classes in Java

WBOY
WBOYOriginal
2024-05-05 09:12:01387browse

The difference between the implementation of interfaces and abstract classes in Java is: interface: provides a collection of abstract methods, and the class implements the methods in the interface; abstract class: provides partial method implementation, and the class inherits the abstract class to obtain partial implementation; the interface can only define method signatures , cannot contain implementation; abstract classes can contain abstract methods and non-abstract methods; classes inherit methods in interfaces by implementing interfaces; classes obtain partial implementation provided by abstract classes by inheriting abstract classes.

Java 中如何实现接口和抽象类

Implementation of interfaces and abstract classes in Java

Interface (Interface)

  • Interface is A set of abstract methods that defines the methods that a class must implement.
  • The interface cannot contain any method implementation, only method declaration.
  • A class can inherit the methods in the interface by implementing the interface.

Implementation interface:

public class Vehicle implements Drivable {

    public void drive() {
        // 驾驶车辆的实现
    }
}

Abstract Class (Abstract Class)

  • Abstract class is an A class that provides partial method implementation.
  • Abstract classes can contain abstract methods and non-abstract methods.
  • A class can obtain part of the implementation provided by the abstract class by inheriting the abstract class.

Implement abstract class:

public class Car extends Vehicle {

    @Override
    public void drive() {
        super.drive();
        // 其他特定的驾驶车辆实现
    }
}

Practical case:

Create an interface and abstract class :

interface Drivable {
    void drive();
}

abstract class Vehicle {
    public abstract void drive();

    public void start() {
        // 公共方法的实现
    }
}

Create a class that implements the interface:

public class Bike implements Drivable {

    @Override
    public void drive() {
        // 驾驶自行车
    }
}

Create a class that inherits the abstract class:

public class Truck extends Vehicle {

    @Override
    public void drive() {
        // 驾驶卡车
    }
}

Usage:

Drivable bike = new Bike();
bike.drive();

Vehicle truck = new Truck();
truck.drive();
truck.start();

The above is the detailed content of How to implement interfaces and abstract classes in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn