杰瑞科技汇

Java中super与extends究竟有何区别?

Of course! Let's break down super and extends in Java. These two keywords are fundamental to object-oriented programming, especially when dealing with inheritance.

Java中super与extends究竟有何区别?-图1
(图片来源网络,侵删)

extends (The "Is-A" Relationship)

The extends keyword is used in a class or interface declaration to signify that the new class (the subclass or child class) is inheriting from an existing class (the superclass or parent class).

This creates an "is-a" relationship. For example, a Dog "is-a" Animal.

Key Concepts of extends:

  1. Inheritance of Members: The subclass automatically gets all the non-private members (fields and methods) from the superclass.
  2. Code Reusability: You can reuse code from the parent class instead of rewriting it.
  3. Method Overriding: The subclass can provide a specific implementation for a method that is already defined in its superclass. This is a core concept of polymorphism.
  4. Constructor Chaining: Constructors are not inherited. However, the subclass constructor must call a superclass constructor (using super()), either explicitly or implicitly.

super (Accessing the Parent)

The super keyword is a reference variable that is used to refer to the immediate parent class object. It's primarily used for three purposes:

  1. To call the superclass's constructor.
  2. To access a member (field or method) from the superclass that is hidden by the subclass.
  3. To explicitly call the superclass's version of an overridden method.

Putting It All Together: A Detailed Example

Let's create a classic Animal and Dog hierarchy to see how extends and super work in practice.

Java中super与extends究竟有何区别?-图2
(图片来源网络,侵删)

Step 1: The Superclass (Animal.java)

This is the parent class. It has fields, a constructor, and methods.

// Animal.java (Superclass)
public class Animal {
    // Field
    protected String name;
    // Constructor
    public Animal(String name) {
        this.name = name;
        System.out.println("Animal constructor called for " + name);
    }
    // Method
    public void eat() {
        System.out.println(name + " is eating.");
    }
    // Method that will be overridden
    public void makeSound() {
        System.out.println(name + " makes a generic sound.");
    }
}

Step 2: The Subclass (Dog.java)

This class extends Animal. It inherits name and eat(), and it adds its own fields and methods. It also overrides makeSound().

// Dog.java (Subclass)
public class Dog extends Animal {
    // New field specific to Dog
    private String breed;
    // Constructor for Dog
    public Dog(String name, String breed) {
        // 1. Using 'super' to call the superclass's constructor
        //    This MUST be the first line in the subclass constructor.
        super(name); // Calls the public Animal(String name) constructor
        this.breed = breed;
        System.out.println("Dog constructor called for " + name + ", breed: " + breed);
    }
    // New method specific to Dog
    public void wagTail() {
        System.out.println(name + " the " + breed + " is wagging its tail.");
    }
    // 2. Overriding a method from the superclass
    @Override // Good practice to annotate overridden methods
    public void makeSound() {
        System.out.println(name + " the " + breed + " says: Woof! Woof!");
    }
    // 3. Using 'super' to access the superclass's version of an overridden method
    public void makeGenericSound() {
        // This will call the original makeSound() from the Animal class
        super.makeSound(); 
    }
}

Step 3: The Main Class to Run (Main.java)

This class demonstrates how to use the objects and see the effects of extends and super.

// Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("--- Creating a Dog object ---");
        // When we create a Dog object, its constructor is called.
        // The Dog constructor immediately calls the Animal constructor using 'super("Buddy")'.
        Dog myDog = new Dog("Buddy", "Golden Retriever");
        System.out.println("\n--- Accessing inherited and own methods ---");
        // Accessing a field from the superclass (Animal)
        System.out.println("Dog's name: " + myDog.name); // name is protected, so accessible in Dog
        // Calling an inherited method (from Animal)
        myDog.eat(); // Buddy is eating.
        // Calling an overridden method (from Dog)
        myDog.makeSound(); // Buddy the Golden Retriever says: Woof! Woof!
        System.out.println("\n--- Using 'super' to call the parent's method ---");
        // Calling a method that uses 'super' to access the parent's version
        myDog.makeGenericSound(); // Buddy makes a generic sound.
    }
}

Expected Output:

--- Creating a Dog object ---
Animal constructor called for Buddy
Dog constructor called for Buddy, breed: Golden Retriever
--- Accessing inherited and own methods ---
Dog's name: Buddy
Buddy is eating.
Buddy the Golden Retriever says: Woof! Woof!
--- Using 'super' to call the parent's method ---
Buddy makes a generic sound.

extends with Interfaces

You can also use extends with interfaces. When an interface extends another interface, it inherits all of its abstract and default methods.

Java中super与extends究竟有何区别?-图3
(图片来源网络,侵删)
// Vehicle.java (Parent Interface)
interface Vehicle {
    void start();
    default void honk() {
        System.out.println("Beep beep!");
    }
}
// ElectricCar.java (Child Interface)
interface ElectricCar extends Vehicle {
    // Inherits start() and honk() from Vehicle
    void charge(); // New abstract method specific to ElectricCar
}
// Tesla.java (Class implementing the child interface)
class Tesla implements ElectricCar {
    @Override
    public void start() {
        System.out.println("Tesla starts silently.");
    }
    @Override
    public void charge() {
        System.out.println("Tesla is charging.");
    }
}

Key Differences & Summary Table

Feature extends super
Type Keyword used in a declaration. Keyword used as a reference variable.
Purpose To establish an inheritance relationship between classes or interfaces. To access members (fields, methods, constructors) of the immediate parent class.
Usage class Dog extends Animal {} super.name;, super.eat();, super("Buddy");
When Used At the beginning of a class or interface definition. Inside a subclass's constructor or methods.
Use Case extends super
Constructor (Not used directly) super() is the first line of a subclass constructor to call the parent's constructor.
Fields A subclass inherits all non-private fields from the parent. Use super.fieldName to access a parent's field that has been shadowed by a field with the same name in the child.
Methods A subclass can override a parent's method to provide its own implementation. Use super.methodName() to explicitly call the parent's version of an overridden method from within the child's method.
Interfaces interface Child extends Parent {} Not used with interfaces.
分享:
扫描分享到社交APP
上一篇
下一篇