Using this Keyword

This program demonstrates usage of this keyword.

Problem Statement

Write a Java program to use this keyword to differentiate between instance variables and parameters.

Source Code

1 class Student {
2 String name; int age;
3 Student(String name,int age){
4 this.name=name;
5 this.age=age;
6 }
7 void display(){
8 System.out.println("Name: "+name+", Age: "+age);
9 }
10 }
11 public class ThisKeyword {
12 public static void main(String[] args) {
13 System.out.println("Eduinq This Keyword");
14 Student s=new Student("Arun",20);
15 s.display();
16 }
17 }

Program Output

Eduinq This Keyword
Name: Arun, Age: 20

Explanation

Constructor parameters shadow instance variables. - this keyword refers to current objects attributes, resolving ambiguity. - Without this, assignment would be unclear between local parameter and instance variable. - This keyword is essential in constructors, setters, and methods where parameter names match instance variable names. Conclusion: Shows how to use this keyword to refer to current object.

Quick Links to Explore