In this tutorial, we will write this keyword program in java. Before that, you should have knowledge on the following topic in Java.
Example of this keyword in Java in constructor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Student { String name; int marks; Student(String name, int marks) { this.name = name; //use of this this.marks = marks; // use of this } void display() { System.out.println("Name: " + name + " marks:" + marks); } } public class main { public static void main (String[] args) { Student st = new Student("Daniel", 90); st.display(); } } |
Output:
Name: Daniel marks:90
this: Invoke current class method:
The method of the current class can be invoked by using this keyword. If this keyword is not used then the compiler automatically adds this keyword while invoking the method.
source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Method { void m1() { System.out.println("This is method m1"); } void m2() { System.out.println("This is method m2"); this.m1(); } } class Main { public static void main (String[] args) { Method m = new Method(); m.m2(); } } |
Output:
This is method m2
This is method m1