Java: “this” Keyword

By Xah Lee. Date: . Last updated: .

In Java there's keyword named this. It can be used inside methods (and Constructors).

The value of this is the reference to the current object.

class C3 {
    int x = 1;
    C3 me () {return this;}
}

public class T4 {
    public static void main(String[] args) {
        C3 c3 = new C3();
        System.out.println( c3.x );           // prints 1
        System.out.println( c3.me().x );      // same as above
        System.out.println( c3.me().me().x ); // same as above
    }
}

In the above example, the method “me” returns “this”. So, c3.me() is equivalent to the object c3 itself. Therefore, c3.x and c3.me().x and c3.me().me().x are all the same.

Example 2

One common use of this is to refer to current class's variable this.var_name or method this.method_name(…).

class OneNumber {
    int n;
    void setValue (int n) {this.n=n;};
}

public class Thatt {
    public static void main(String[] args) {
        OneNumber x = new OneNumber();
        x.setValue(3);
        System.out.println( x.n );
    }
}

In the above example, the method “setValue” tries to set class variable “n” to the value of the method's argument also named “n”. Because the name n is already used in the parameter name, so n=n is absurd. The workaround is to use the “this” keyword to refer to the object. So, this.n is the class variable n, and the second n in this.n=n is the method's argument.

Calling Constructor

Another common use of this is to call constructor.

class BB {
    int x;

    BB (int n) {this.x = n;}
    BB () {this(1);}
 
}

public class AA {
    public static void main(String[] args) {
        BB bb = new BB();
        System.out.println( bb.x );
    }
}

Example 3

Another practical example of using “this” is when you need to pass your current object to another method. Example:

class B {
    int n;
    void setMe (int m) {
        C h = new C();
        h.setValue(this, m);
    };
}

class C {
    void setValue (B obj, int h) {obj.n=h;};
}

public class A {
    public static void main(String[] args) {
        B x = new B();
        x.setMe(3);
        System.out.println( x.n );
    }
}

In the above example, B has a member variable n. It has a method setMe. This method calls another class method and passing itself as a object.

There is also a “super” keyword used to refer to the parent class. See “super” keyword.

Java

  1. Install
  2. javac java jar javadoc

Java Basics

  1. Print String
  2. Strings
  3. Power Function
  4. Java Types and Type Conversion
  5. Function
  6. Arrays

Class, Inheritance

  1. extends
  2. Constructor
  3. Constructor Return Type
  4. Extending a Class that has Explicit Constructors
  5. static
  6. this
  7. super
  8. Access Specifiers

Abstract class, Interface

  1. abstract
  2. Interface

Package

  1. Package

Misc

  1. Collection, Map
  2. Read/Write File
  3. Convert File Encoding
  4. Complex Numbers in Java
  5. Unicode
  6. Number Literals