杰瑞科技汇

Java中implements关键字到底有什么用?

Of course! In Java, the implements keyword is a fundamental part of the language, used to achieve interface implementation.

Java中implements关键字到底有什么用?-图1
(图片来源网络,侵删)

Let's break it down with clear explanations, analogies, and code examples.

The Core Concept: What is an Interface?

Think of an interface as a contract or a blueprint.

  • What it specifies: An interface defines a set of methods that a class must implement. It says, "Any class that signs this contract (implements this interface) must know how to do these things."
  • What it doesn't specify: An interface does not provide the implementation for those methods. It only lists the method signatures (name, parameters, return type).
  • The Analogy: Imagine a Drivable contract. To be considered "Drivable," a vehicle must be able to start(), stop(), and accelerate(). A Car, a Motorcycle, and even a Scooter can all be Drivable, but they implement these actions in their own unique ways. The Drivable interface is the contract they all follow.

The Role of the implements Keyword

The implements keyword is how a class signs the contract and agrees to provide the implementations for all the methods defined in an interface.

When a class uses implements, it is making a promise: "I will provide a body for every method declared in this interface."

Java中implements关键字到底有什么用?-图2
(图片来源网络,侵删)

Syntax

The syntax for using implements is straightforward:

public class MyClass implements SomeInterface {
    // ... class members ...
    // You MUST provide an implementation for all methods in SomeInterface
    @Override
    public void methodFromInterface() {
        // implementation goes here
    }
}

Code Example: Step-by-Step

Let's build the Drivable example.

Step 1: Define the Interface (Drivable.java)

This is the contract. It declares the methods that any "Drivable" object must have.

// Drivable.java
public interface Drivable {
    // All methods in an interface are public and abstract by default.
    // You don't need to write the 'public abstract' keywords, but it's good practice to remember.
    void start();      // Contract: You must have a start() method.
    void stop();       // Contract: You must have a stop() method.
    void accelerate(int speed); // Contract: You must have this accelerate method.
}

Step 2: Implement the Interface in a Class (Car.java)

Now, the Car class signs the Drivable contract and provides its own specific implementations.

Java中implements关键字到底有什么用?-图3
(图片来源网络,侵删)
// Car.java
public class Car implements Drivable {
    @Override // Good practice to use @Override to ensure you're matching the interface method signature
    public void start() {
        System.out.println("Car started with a key turn. Vroom!");
    }
    @Override
    public void stop() {
        System.out.println("Car stopped by pressing the brake pedal.");
    }
    @Override
    public void accelerate(int speed) {
        System.out.println("Car is accelerating. Current speed: " + speed + " km/h");
    }
}

Step 3: Create Another Implementation (Motorcycle.java)

Notice how Motorcycle also implements Drivable but does things differently. This demonstrates polymorphism.

// Motorcycle.java
public class Motorcycle implements Drivable {
    @Override
    public void start() {
        System.out.println("Motorcycle started with a button and a kick. Vroooom!");
    }
    @Override
    public void stop() {
        System.out.println("Motorcycle stopped by squeezing the clutch and brake.");
    }
    @Override
    public void accelerate(int speed) {
        System.out.println("Motorcycle is revving up to " + speed + " km/h!");
    }
}

Step 4: Use the Classes

Now you can treat both Car and Motorcycle objects as Drivable objects. This is a powerful feature of Java.

// Main.java
public class Main {
    public static void main(String[] args) {
        // We can use the interface type to reference the objects
        Drivable myCar = new Car();
        Drivable myBike = new Motorcycle();
        // We can call the methods defined in the interface
        // The JVM knows which actual implementation to run (Car's or Motorcycle's)
        myCar.start();
        myCar.accelerate(80);
        myCar.stop();
        System.out.println("--------------------");
        myBike.start();
        myBike.accelerate(60);
        myBike.stop();
    }
}

Output of the Example:

Car started with a key turn. Vroom!
Car is accelerating. Current speed: 80 km/h
Car stopped by pressing the brake pedal.
--------------------
Motorcycle started with a button and a kick. Vroooom!
Motorcycle is revving up to 60 km/h!
Motorcycle stopped by squeezing the clutch and brake.

Key Rules and Important Details

  1. Implement All Methods: If a class implements an interface, it must provide an implementation for every single method in that interface. If you even forget one, the compiler will give you an error.

  2. Method Signatures Must Match: The method in your class must have the exact same name, return type, and parameter list as the method in the interface.

  3. Access Level: Methods in an interface are public by default. When you implement them in your class, they must also be public (or a more accessible level, but public is the standard).

  4. A Class Can Implement Multiple Interfaces: This is one of the biggest advantages of interfaces over abstract classes (a class can only extend one abstract class).

    public class FlyingCar implements Drivable, Flyable {
        // Must implement methods from BOTH Drivable and Flyable interfaces
        @Override
        public void start() { /* ... */ }
        @Override
        public void stop() { /* ... */ }
        @Override
        public void accelerate(int speed) { /* ... */ }
        @Override
        public void takeOff() { /* ... */ }
        @Override
        public void land() { /* ... */ }
    }
  5. Default and Static Methods (Java 8+): Interfaces can now contain default and static methods, which have implementations.

    • default method: The interface provides a default implementation. A class implementing the interface can choose to override it or use the default. This is great for adding new functionality to an interface without breaking all existing implementations.
    • static method: Belongs to the interface itself, not to any instance of a class that implements it. You call it directly on the interface (e.g., MyInterface.staticMethod()).
    public interface Drivable {
        void start();
        void stop();
        // A default method with a default implementation
        default void honk() {
            System.out.println("Honk! Honk!");
        }
    }
    // Car can now just use the default honk() method
    public class Car implements Drivable {
        // ... other implementations ...
    }

Summary: implements vs. extends

Keyword Purpose Relationship Inheritance
implements A class fulfills a contract defined by an interface. "Is-a" / "Can-do" relationship. A Car is a Drivable. A class can implement multiple interfaces.
extends A class inherits state and behavior from another class. "Is-a" relationship. A Dog is a Animal. A class can only extend one parent class.

In short, implements is your tool for defining what a class can do (its capabilities), while extends is for defining what a class is (its type).

分享:
扫描分享到社交APP
上一篇
下一篇