Home
Map
this KeywordUse the this-keyword to reference the current instance of the class. Pass a this reference.
Java
This page was last reviewed on Dec 5, 2022.
This. A class has methods. Within these methods, we can reference the current instance of the class. We use the "this" keyword—we can access fields, other methods and the instance itself.
This constructor. We can invoke a constructor with the this() syntax. With this technique, we can fill in default arguments from a simpler constructor.
Constructor
Some details. With "this," we become specific about what a name refers to. When an argument and a field have the same name, we can use "this" to indicate the field, not the argument.
Here The name "code" would refer to the argument if it had no "this" before the name. We use a composite name.
class Cat { int code = 10; public void pet(int code) { // Refers to the code field, not the argument. System.out.println(this.code); } } public class Program { public static void main(String[] args) { Cat cat = new Cat(); cat.pet(5); } }
10
This, class references. We can pass the present class to another method with the "this" reference. We forward a class to another method.
class Bird { public String color = "red"; public void call() { // Pass this class instance to another method. Program.analyze(this); } } public class Program { public static void analyze(Bird bird) { // This method does something with a Bird class. System.out.println(bird.color); } public static void main(String[] args) { // Start here. Bird bird = new Bird(); bird.call(); } }
red
Some notes. Sometimes we want to pass a class to a static method that acts upon that class instance. We use the "this" keyword as an argument.
When developing a program, I like it to be clear. I do not like ambiguous statements. So I tend to use "this" when possible, unless it does not add any clarity.
Another keyword, super, can be used much like the "this" keyword. But with super we are relying on an inheritance relation. These keywords help make our programs clearer.
super
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.