杰瑞科技汇

Java中this与other关键字的区别与应用场景?

Of course! This is a fantastic question because "this" and "other" are fundamental concepts in Java, but they operate in very different ways.

Java中this与other关键字的区别与应用场景?-图1
(图片来源网络,侵删)

Let's break them down.


this in Java

this is a keyword in Java. It's a special reference variable that every non-static method (and constructor) automatically has. It refers to the current object whose method or constructor is being called.

Think of it as a pronoun, like "myself" or "ourselves." If a method inside an object says "this," it means "the object I am currently working on."

Key Uses of this

a) To Refer to the Current Object's Instance Variables This is the most common use. It helps to distinguish between instance variables (variables belonging to the object) and local variables (variables inside a method or constructor) that have the same name.

Java中this与other关键字的区别与应用场景?-图2
(图片来源网络,侵删)
public class Person {
    private String name; // This is an instance variable
    public Person(String name) {
        // The 'name' on the right is the local variable from the constructor parameter.
        // The 'name' on the left is the instance variable.
        // Without 'this', we would be assigning the local variable to itself (no effect).
        this.name = name; // 'this.name' refers to the instance variable.
    }
    public void printName() {
        System.out.println("My name is: " + this.name); // 'this.name' is clear and explicit.
    }
}

b) To Call the Current Object's Other Methods You can use this to call another method from within the same object.

public class Calculator {
    public int add(int a, int b) {
        System.out.println("Adding...");
        return a + b;
    }
    public int calculateSum(int a, int b) {
        // 'this.add()' calls the add method of the same object.
        int result = this.add(a, b);
        System.out.println("Sum is: " + result);
        return result;
    }
}

c) To Call a Constructor from Another Constructor (Constructor Chaining) this can be used to call a constructor from within another constructor in the same class. This must be the very first line of the calling constructor.

public class Student {
    private String name;
    private int age;
    // Constructor 1
    public Student(String name) {
        // Calls the second constructor (Student(String, int))
        this(name, 18); // Default age is 18
    }
    // Constructor 2
    public Student(String name, int age) {
        this.name = name; // Using 'this' to distinguish
        this.age = age;
    }
}

d) To Return the Current Object This allows you to chain method calls together, which is very common in "Builder" patterns.

public class StringBuilderExample {
    private String value = "";
    public StringBuilderExample append(String str) {
        this.value += str;
        // Return 'this' (the current object) to allow for chaining.
        return this;
    }
    public String toString() {
        return this.value;
    }
    public static void main(String[] args) {
        StringBuilderExample sb = new StringBuilderExample();
        sb.append("Hello").append(" ").append("World!"); // Method chaining!
        System.out.println(sb); // Prints "Hello World!"
    }
}

"Other" in Java

"Other" is not a keyword in Java. It's a general term used in programming to refer to:

Java中this与other关键字的区别与应用场景?-图3
(图片来源网络,侵删)
  1. Other objects: An instance of a class different from the current one.
  2. Other variables/methods: Any variable or method that is not the one currently being discussed.
  3. Other classes: Any class in your project or from a library that you are using.

You cannot write other.something() in your code. Instead, you use a variable that holds a reference to another object.

How "Other" Objects Are Handled

a) Passing an Object as a Parameter to a Method

This is the most common way for one object to interact with another. You pass a reference to the "other" object as an argument.

public class Garage {
    // This method takes a Car object as a parameter. The Car is the "other" object.
    public void parkCar(Car carToPark) {
        System.out.println("Parking the car: " + carToPark.getModel());
        // Here, we are interacting with the 'other' object (carToPark)
        // by calling its 'getModel()' method.
    }
}
public class Car {
    private String model;
    public Car(String model) {
        this.model = model;
    }
    public String getModel() {
        return this.model; // 'this' refers to the Car object
    }
}
// In your main method:
Garage myGarage = new Garage();
Car myTesla = new Car("Model S");
myGarage.parkCar(myTesla); // 'myTesla' is the "other" object being passed to the method.

b) Creating an Instance of Another Class

You can create an object of another class and store its reference in a variable.

public class BankAccount {
    private double balance;
    public void deposit(double amount) {
        this.balance += amount;
    }
    public void transferFunds(BankAccount otherAccount, double amount) {
        // 'this' is the account we are transferring FROM.
        // 'otherAccount' is the "other" object, the account we are transferring TO.
        if (this.balance >= amount) {
            this.balance -= amount;
            otherAccount.deposit(amount); // We call a method on the "other" object.
            System.out.println("Transfer successful.");
        } else {
            System.out.println("Insufficient funds.");
        }
    }
}

Summary Table: this vs. "Other"

Feature this "Other"
Type A reserved keyword in Java. A general concept/term, not a keyword.
Meaning Refers to the current object whose method is being executed. Refers to any other object or entity in the program.
Usage Used inside a method or constructor. Used when you have a reference to another object (e.g., a variable).
Example this.name = name; garage.parkCar(myCar);
Purpose To resolve name conflicts, call other methods/constructors of the same object, or return the current object. To allow objects to interact with each other, pass data, or delegate tasks.

Analogy

Imagine you are in a room (this is you, the current object).

  • Using this: You point to yourself and say, "I am going to open the door." You are referring to yourself.
  • Using "other": You see a friend in the room (the "other" object) and say, "You should open the door." You are referring to another entity.

In Java, this is the "I" and the object you're passing to a method is the "You."

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