Java 'this' Keyword Tutorial

this keyword is a reference variable used in Java to refer to the current object. It can be used to refer to current class instance variables, methods, and constructors strings.

Usage of Java 'this' Keyword

  • 1. To refer current class instance variable

    The this keyword can be used to refer to the current class instance variable. If there is ambiguity between the instance variables and parameters (i.e. if they have the same name), this keyword resolves the problem of ambiguity.

    public class Bird {
        private String name;
    
        public Bird(String name) {
            this.name = name;
        }
    }
  • 2. To invoke current class constructor

    The this() constructor call can be used to invoke the current class constructor.

    Note: Calling `this()` must be the first statement in the constructor.
    public class Bird {
        private String name;
        private String color;
    
        public Bird(String name) {
            this.name = name;
        }
    
        public Bird(String name, String color) {
            this(name);
            this.color = color;
        }
    }
  • 3. To invoke current class method

    You may invoke the method of the current class by using the `this` keyword. If you don't use `this` keyword, compiler automatically adds `this` keyword while invoking the method.

  • 4. To return the current class instance

    We can return the `this` keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive).

    public Bird getBird() {
        return this;
    }

Frequently Asked Questions

What will I learn here?

This page covers the core concepts and techniques you need to understand the topic and progress confidently to the next lesson.

How should I use this page?

Start with the overview, then follow the section links to deepen your understanding. Use the table of contents on the right to jump to specific sections.

What should I read next?

Use the navigation below to continue to the next lesson or explore related topics.