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.
Interface (Interface)
Implementation interface:
public class Vehicle implements Drivable { public void drive() { // 驾驶车辆的实现 } }
Abstract Class (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!