Course contentsShow
← Java
Lesson 205 of 2,8705. Methods and Function CallsFree lesson

Static vs Instance Methods: When to Use this

Understand the difference between methods that operate on instances versus class-level static methods.

Static vs Instance Methods: When to Use this

What You'll Learn

You'll discover when methods belong to individual objects versus the class itself, and how this connects methods to their specific object.

The Core Distinction

Every method in Java is either static (belongs to the class) or an instance method (belongs to each object created from the class).

Instance methods operate on specific objects. Each object has its own copy of the data (fields), and instance methods work with that particular object's data. The keyword this refers to "the current object" — the one whose method was called.

Static methods belong to the class itself, not to any particular object. They can't use this because there's no specific object involved. Think of them as utility functions or class-level operations.

Analogy

Imagine a BankAccount class. An instance method like deposit(100) needs to know which specific account to deposit into — that's where this points. A static method like convertCurrency(50, "USD") doesn't need any particular account; it just performs a calculation for anyone who asks.

When to Use this

Inside an instance method, this refers to the object that called the method. You've already used it when parameter names matched field names:

public void setBalance(double balance) {
    this.balance = balance; // 'this.balance' is the field, 'balance' is the parameter
}

You can only use this inside instance methods, never in static methods.

Choosing Between Static and Instance

  • Use instance methods when you need to access or modify object-specific data
  • Use static methods when the operation doesn't depend on any particular object's state

Key Takeaway: Instance methods work with individual objects and can use this to refer to the current object; static methods belong to the class itself and have no access to this or instance-specific data.