An Explanation of ‘this’ in Java
As every Java programmer should know, code within any non-static method can access the current object via a special reference called ‘this’. Just how this works may not be immediately obvious so I’ve taken a moment to explain it here.
The best way I know to explain ‘this’ properly is by taking a look at how object oriented languages actually work and comparing them to their older siblings: structured programming languages.
In a structured programming language (like C or Pascal for example) you store data in a struct or a record and reuse code by creating functions. Moreover, when you call a function you may pass them records to work with.
So before we start looking at Java, let’s consider some pseudo-code in an imaginary structured programming language. First we’ll define an account record structure in this language, and then a simple function that can be used to update them:
//define an account record structure with two fields (balance and overdraft)
record account {
int balance;
int overdraft;
}
//now define a function for updating the account's balance
void deposit(account a, int amount) {
a.balance += amount;
}
So, given an account record ‘a’, we could use our imaginary language to deposit £100 by calling the above function as follows:
//create a new account record a = new account(); //update the account's balance using the function deposit(a, 100);
In an Object Oriented language like Java we would more likely define an account class with a deposit method:
public class Account {
private int balance;
public void deposit(int amount) {
balance += amount;
}
}
and use it like this:
Account a = new Account(); a.deposit(100);
As we know, Object Orientation is just a higher level programming abstraction. Therefore, the code that you’d write in Java is just another way of expressing what you’d write in a procedural language.
In fact, the Java compiler actually produces bytecode that looks more like procedural code. For example, a method call like this:
a.deposit(100)
would actually be compiled as though it were a function call:
deposit(a, 100);
and our deposit method would be treated likewise and compiled as though it were:
void deposit(Account this, int amount) {
this.balance += amount;
}
Note that the compiler has restructured the statement as a function and introduced an initial parameter called ‘this’ that will be a reference to the object that the method is being invoked on. As you can see then, it is this ‘this’ variable that allows you to refer explicitly to the current object.
The one gotcha here is if you define a method with the static modifier. Static methods don’t require that an object is created before they are called; they are generally just called via the class name, like Math.min(…) for example. In this sense they really are just like a procedural language function so the compiler does not introduce a ‘this’ parameter. Clearly then, this is why you cannot access ‘this’ from within static methods.
