Home
Java
this Keyword
Updated Dec 5, 2022
Dot Net Perls
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen