Java中this(var)与this.var的区别是什么?
this(var) and this.var in Java Great question! Let's break down these two Java constructs clearly, using your provided Clock class as a concrete example.
1. this.var – Accessing Instance Variables
this.var is used to refer to the instance variable (member field) of the current object. It's most commonly used when a method/constructor parameter has the same name as the instance variable (a name collision), to explicitly tell the compiler which one you mean.
Looking at your code:
private Clock(long time) { this.time = time; }
Here:
this.timerefers to the private instance variablelong time = 0;defined at the top of theClockclass.- The right-hand side
timeis the parameter passed into this constructor. - Without
this., the compiler would assume you're assigning the parameter to itself (a no-op), which isn't what we want.
You can also use this.var even when there's no name collision, just to make your code clearer that you're accessing an instance variable.
2. this(var) – Calling Another Constructor in the Same Class
this(...) is a constructor call – it invokes another constructor from the same class. This is part of Java's constructor chaining, which helps reduce code duplication by reusing initialization logic.
Key rules for this(...):
- It must be the first statement in the constructor where it's used.
- The parameters inside the parentheses must match the parameter list of another constructor in the class.
In your example:
public Clock(long time, long timeOffset) { this(time); // Calls the private Clock(long time) constructor this.time += timeOffset; }
Here, this(time) calls the single-parameter private constructor first. That constructor sets the time instance variable to the passed time value. Then, we add timeOffset to this.time to get the final value.
Without constructor chaining, we'd have to duplicate the this.time = time; line in this constructor – which is messy if we ever need to change how time is initialized later.
Core Summary of Differences
- Purpose:
this.varaccesses an instance variable of the current object.this(...)invokes another constructor in the same class to reuse initialization code.
- Position:
this.varcan be used anywhere in an instance method or constructor (as long as you're in an instance context).this(...)must be the very first line of a constructor.
- Syntax:
this.varuses a dot followed by the variable name.this(...)uses parentheses with parameters matching another constructor's signature.
内容的提问来源于stack exchange,提问作者Manoj Kumar Krishnamurthy

