Java: The 'this' reference (with examples)

Every ordinary (non-static) Java method runs in the context of an object, and this refers to that object.

If you have an object myObj, and you call myObj.someMethod() then someMethod() will run in the context of myObj.

Example: Printing the same object twice:

class MyClass {
    public void printThis() {

MyClass obj = new MyClass();

System.out.println(obj);  // prints "MyClass@4aa298b7"
obj.printThis();          // prints "MyClass@4aa298b7"

When is the 'this' reference useful?

Sometimes there's a name clash between fields and local variables or arguments. It's especially common in constructors and setter methods.

Example: Disambiguating between fields and constructor arguments.

class Person {
    String firstName;
    String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;

You may also see it used when passing the current object as an argument to another method.

Example: Registering this object as a listener.

class EventHandler implements EventListener {

    public EventHandler(EventSource source) {
        // Register this object as a listener
    public void changeEvent(Event e) {
        // respond to event

There's also a more complex scenario where this is prefixed with a class to disambiguate between different static types. See article Class.this explained


Be the first to comment!