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.
Examplepublic 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 −
OutputHello World
Following example shows a usecase of this keyword in case of inheritance.
Exampleclass 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4