Instance methods and this
An instance method is a method without static: it runs with one object as its receiver and can read and write that object's fields. The receiver is named this inside the method, and a method may return it, which is how a chain of calls works.
Instance methods
The account below keeps one field and lets the methods change it. A deposit adds, a withdrawal checks the balance first and answers whether it happened, and the getter returns the value without changing it.
The file Account.java:
public class Account {
private int balance;
Account(int balance) {
this.balance = balance;
}
void deposit(int amount) {
this.balance += amount;
}
boolean withdraw(int amount) {
if (amount > balance) {
return false;
}
this.balance -= amount;
return true;
}
int getBalance() {
return balance;
}
Account withBonus(int amount) {
deposit(amount);
return this;
}
public static void main(String[] args) {
Account account = new Account(100);
account.deposit(50);
System.out.println("after deposit: " + account.getBalance());
System.out.println("withdraw 30: " + account.withdraw(30));
System.out.println("balance: " + account.getBalance());
System.out.println("withdraw 500: " + account.withdraw(500));
System.out.println("balance: " + account.getBalance());
account.withBonus(10).withBonus(20);
System.out.println("after bonus: " + account.getBalance());
}
}
javac -Xlint:all Account.java
java Account
after deposit: 150
withdraw 30: true
balance: 120
withdraw 500: false
balance: 120
after bonus: 150
The refused withdrawal returns false and leaves the balance at 120, which is the difference between a method that reports a failure and one that throws an exception. Lesson 038 turns the false into an exception; lesson 047 builds the account with a statement.
this
Inside an instance method, this is the object the method was called on. account.deposit(50) runs deposit with this == account, so this.balance += amount changes that account and no other. A second account has its own this when its methods run.
The word is optional when no local variable hides the field, and the compiler accepts both balance and this.balance in getBalance. It is required when a parameter has the same name as the field, as in the constructor, and it is the value a method returns when it wants to give the caller the object back.
Getters and setters
A private field with a public getter is the usual way to expose a value without exposing the storage. A setter is a method that validates before it assigns, and a setter that silently ignores a bad value is the smallest form of validation a class can have.
public class Getters {
private String name;
private int age;
Getters(String name, int age) {
this.name = name;
this.age = age;
}
String getName() {
return name;
}
int getAge() {
return age;
}
void setName(String name) {
this.name = name;
}
void setAge(int age) {
if (age >= 0) {
this.age = age;
}
}
public static void main(String[] args) {
Getters person = new Getters("Ada", 36);
person.setName("Grace");
person.setAge(85);
person.setAge(-1);
System.out.println(person.getName() + " " + person.getAge());
}
}
javac -Xlint:all Getters.java
java Getters
Grace 85
The second setAge call passes -1 and the setter ignores it, so the age stays 85. A setter that reports the failure, with a boolean or an exception, is a decision of the class; silence is the smallest version and the one a field cannot give.
A method that returns this
withBonus returns this after the deposit, so the next call can be written on the same line: account.withBonus(10).withBonus(20). The style is called a fluent interface, and it is the reason StringBuilder can be chained in lesson 025.
A method that returns this does not create an object and does not copy one; it returns the same reference the caller already had. A method that returns a copy is a different operation, and the copy constructor of the next lesson is how it is written.
Exercises
- Add a transferTo(Account other, int amount) method to Account.java and use it from main.
- Make withdraw return the new balance instead of a boolean, and decide what a refused withdrawal should return.
- Give Getters.java a setter for the name that rejects an empty string.
- Write a chain of three calls on one account and predict the balance before you run it.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is
thisinside an instance method?Answer
The object the method was called on
this is the receiver of the call, which is the object whose fields the method reads and writes.
-
When is
thisrequired before a field name?Answer
When a local variable or parameter has the same name
A parameter of the same name hides the field, and this.field selects the field.
-
What does a method that returns
thisgive the caller?Answer
The same object, so calls can be chained
The reference is returned unchanged, which is what a fluent chain needs.
-
What does this program print?
public class Q1 { public static void main(String[] args) { Counter c = new Counter(); c.increment(); c.increment(); System.out.println(c.value); } } class Counter { int value; void increment() { value++; } }Answer
2
Both calls run on the same object and increment its one field.
-
What does this program print?
public class Q2 { public static void main(String[] args) { Counter a = new Counter(); Counter b = new Counter(); a.increment(); System.out.println(a.value + " " + b.value); } } class Counter { int value; void increment() { value++; } }Answer
1 0
Each object has its own value field, and only a was incremented.
-
What does this program print?
public class Q3 { public static void main(String[] args) { Acc acc = new Acc(10); acc.add(5).add(5); System.out.println(acc.balance); } } class Acc { int balance; Acc(int balance) { this.balance = balance; } Acc add(int amount) { balance += amount; return this; } }Answer
20
add returns the same object, and the second call adds 5 again.
-
What does this program print?
public class Q4 { public static void main(String[] args) { Acc acc = new Acc(); acc.setLimit(-1); System.out.println(acc.limit); } } class Acc { int limit = 5; void setLimit(int limit) { if (limit >= 0) { this.limit = limit; } } }Answer
5
The setter ignores the negative value, so the field keeps its initial 5.
-
What does this program print?
public class Q5 { public static void main(String[] args) { Acc acc = new Acc(10); System.out.println(acc.getBalance()); } } class Acc { private int balance; Acc(int balance) { this.balance = balance; } int getBalance() { return this.balance; } }Answer
10
The getter returns the field the constructor stored, and this.balance is the same field.
-
What is a getter?
Answer
A method that returns the value of a field
A getter reads a field and returns it, usually without changing anything.
-
What does this program print?
public class Q6 { public static void main(String[] args) { Pair p = new Pair(3, 4); System.out.println(p.sum()); } } class Pair { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } int sum() { return a + b; } }Answer
7
The instance method reads both fields of its object and returns their sum.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev