Java Tutorial

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java List Interface

Java Queue Interface

Java Map Interface

Java Set Interface

Java Data Structures

Java Collections Algorithms

Java Miscellaneous

Advanced Java

Java APIs & Frameworks

Java Useful Resources

Java - this keyword



this keyword is a very important keyword to identify an object. Following are the usage of this keyword.

  • this can be used to get the current object.

  • this can be used to invoke current object's method.

  • this() can be used to invoke current class constructor.

  • this can be passed as a parameter to a method call.

  • this can be passed as a parameter to a constructor.

  • this can be used to return the current object from the method.

Following example shows a simple usecase of this keyword.

Example

public class JavaTester {
   private String message;
   public JavaTester(String message){
      this.message = message;
   }
   public void printMessage(){
      System.out.println(message);
   }
   public static void main(String args[]) {
      JavaTester tester = new JavaTester("Hello World");
      tester.printMessage();
   }
}

Compile and run the above program. This will produce the following result −

Output

Hello World

Following example shows a usecase of this keyword in case of inheritance.

Example

class Superclass {
   int age;

   Superclass(int age) {
      this.age = age; 		 
   }

   public void getAge() {
      System.out.println("The value of the variable named age in super class is: " +age);
   }
}

public class Subclass extends Superclass {
   Subclass(int age) {
      super(age);
   }

   public static void main(String args[]) {
      Subclass s = new Subclass(24);
      s.getAge();
   }
}

Output

Compile and execute the above code using the following syntax.

javac Subclass
java Subclass

In this example, we're referring to current object in SuperClass constructor using this keyword.

java_basic_syntax.htm
Advertisements