HomeSearch

Java This Keyword

This Java example uses the this-keyword to reference the current instance of the class. It passes this reference.
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.
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.

Java program that uses this 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); } } Output 10
This, class references. We can pass the present class to another method with the "this" reference. We forward a class to another method.
Java program that passes this reference 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(); } } Output red
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: this
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
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls