this keyword

This keyword in java

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter.


 int a;
basic(int a){
a=a; // It will give you error

}
So to solve this problem we use this keyword:
 int a;
basic(int a){
this.a=a;

}
Full program of this keyword..


package com.ritesh;
class basic{
int a;
basic(int a){ //constructor
this.a=a; // this can be used to refer current class instance variable.

}
public int returner(int a){ //method which return a
return a;
}

}

public class supe {
public static void main(String[] args) {
basic b1=new basic(5);
System.out.println(b1.a);
}
}


Some other example..
class Main {

    int age;
    Main(int age){
        this.age = age;
    }

    public static void main(String[] args) {
        Main obj = new Main(8);
        System.out.println("obj.age = " + obj.age);
    }
}

Comments