杰瑞科技汇

this在final修饰的方法中能指向什么?

Of course! In Java, this and final are two very important but distinct keywords. They serve different purposes but are fundamental to writing robust, object-oriented code.

this在final修饰的方法中能指向什么?-图1
(图片来源网络,侵删)

Let's break them down individually and then see how they can interact.


Part 1: this Keyword

The this keyword in Java is a reference to the current object—the object whose method or constructor is currently being called. Think of it as a way for an object to refer to itself.

It has several primary uses:

To Distinguish Between Instance Variables and Parameters

This is the most common use. If a parameter of a method has the same name as an instance variable, this is used to refer to the instance variable.

this在final修饰的方法中能指向什么?-图2
(图片来源网络,侵删)
public class Person {
    private String name; // Instance variable
    // Constructor with a parameter 'name'
    public Person(String name) {
        // Without 'this', the parameter 'name' would just assign to itself.
        // 'this.name' refers to the instance variable of the class.
        this.name = name;
    }
    public void printName() {
        System.out.println(this.name); // 'this.name' is the instance variable
    }
}

To Invoke Another Constructor in the Same Class (Constructor Chaining)

You can use this(...) to call another constructor from within a constructor. This must be the first statement in the constructor.

public class Student {
    private String name;
    private int age;
    // Constructor 1: No-arg constructor
    public Student() {
        // Calls the second constructor, providing default values
        this("Unknown", 0);
    }
    // Constructor 2: Two-arg constructor
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

To Pass the Current Object as an Argument

You can pass the current object to another method or a constructor.

public class Calculator {
    public void performCalculation(CalculationStrategy strategy) {
        // Pass the current object (this) to the strategy object
        strategy.execute(this);
    }
}
// Example of a strategy interface
interface CalculationStrategy {
    void execute(Calculator calculator);
}

To Return the Current Object

This is often used in a "fluent interface" style, where multiple methods can be chained together.

public class StringBuilderExample {
    private StringBuilder sb = new StringBuilder();
    public StringBuilderExample append(String text) {
        sb.append(text);
        // 'return this' allows for method chaining
        return this;
    }
    public String build() {
        return sb.toString();
    }
    public static void main(String[] args) {
        String result = new StringBuilderExample()
                          .append("Hello, ")
                          .append("World!")
                          .build();
        System.out.println(result); // Output: Hello, World!
    }
}

Part 2: final Keyword

The final keyword is a modifier that can be applied to classes, methods, and variables. It signifies that something cannot be changed.

this在final修饰的方法中能指向什么?-图3
(图片来源网络,侵删)

final Variables

A final variable is a constant. Once initialized, its value cannot be changed.

  • For primitive types (e.g., int, double): The value cannot be reassigned.

    final int MAX_SPEED = 120;
    // MAX_SPEED = 121; // COMPILE ERROR: cannot assign a value to final variable MAX_SPEED
  • For reference types (e.g., String, objects): The reference itself cannot be changed (i.e., you cannot make it point to a different object). However, the state of the object it points to can still be modified, unless the object's own fields are also final.

    final StringBuilder myBuilder = new StringBuilder("Hello");
    // myBuilder = new StringBuilder("Goodbye"); // COMPILE ERROR: cannot assign a value to final variable myBuilder
    // This is allowed because we are not changing the reference, but the object's state.
    myBuilder.append(" World!");
    System.out.println(myBuilder.toString()); // Output: Hello World!

final Methods

A final method cannot be overridden by a subclass. This is used to prevent modification of a method's behavior in a subclass.

public class Vehicle {
    public final void startEngine() {
        System.out.println("Engine started.");
    }
}
public class Car extends Vehicle {
    // @Override
    // public void startEngine() { // COMPILE ERROR: Cannot override a final method
    //     System.out.println("Car engine started with a key.");
    // }
}

final Classes

A final class cannot be extended or subclassed. This is often used for security, immutability, or to prevent breaking changes in a library.

public final class String { // This is a simplified example. The real java.lang.String is final.
    // ... class implementation ...
}
// public class MyString extends String { // COMPILE ERROR: Cannot inherit from final String
// }

Part 3: How this and final Interact

This is where it gets interesting. You can declare an instance variable as final. When you do this, you must initialize it exactly once. This is where this becomes crucial for that initialization.

Scenario: A final instance variable that must be initialized in a constructor.

Since a final variable cannot be left uninitialized, and you often can't know its value until the object is being created, you must assign it in the constructor. this is used to distinguish the final variable from the constructor's parameter.

public class BankAccount {
    // The account number is final; it cannot be changed after the account is created.
    private final String accountNumber;
    public BankAccount(String accountNumber) {
        // Use 'this' to assign the parameter to the final instance variable.
        // This is the one and only place where 'accountNumber' can be set.
        this.accountNumber = accountNumber;
    }
    public String getAccountNumber() {
        return this.accountNumber; // 'this' is used here for clarity, though often optional.
    }
    // You cannot have a setter for a final variable!
    // public void setAccountNumber(String accountNumber) {
    //     this.accountNumber = accountNumber; // COMPILE ERROR
    // }
}

Key Points of Interaction:

  1. Initialization is Mandatory: A final instance variable must be initialized in the constructor (or at the point of declaration).
  2. this is the Tool: The this keyword is the standard mechanism for performing that initialization from within the constructor, especially when the parameter name is the same as the variable name.
  3. One-Time Assignment: Because the variable is final, the assignment using this can only happen once, which is enforced by the compiler.

Summary Table

Keyword Purpose Common Use Cases
this A reference to the current object. Disambiguate variable names (this.name = name;).
Chain constructors (this(...)).
Pass the current object to a method.
Return the current object for fluent APIs.
final A modifier meaning cannot be changed. Variables: Create constants (final int MAX_SIZE = 100;).
Methods: Prevent overriding (for security or design).
Classes: Prevent inheritance (for security or immutability).

In short:

  • Use this when an object needs to talk about or refer to itself.
  • Use final when you want to make something unchangeable. When you combine them (a final instance variable), this is the primary tool you use to give that unchangeable variable its one and only value.
分享:
扫描分享到社交APP
上一篇
下一篇