C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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