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.
We can invoke a constructor with the this()
syntax. With this technique, we can fill in default arguments from a simpler constructor.
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.
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
class
referencesWe 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
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.