this keyword in java

I was always wondering about the use of this keyword in java. Normally what you will find when browse through some website is . this keyword can be used in any methods to refer to the current object.But what the heck does it really mean. let us see the condition when we normally make the use of this keyword.

 class Demo
        int a,b;
        public void display(int a,int b)

So why do we have to use the this keyword here.
-At first we all have to know this rules we can’t have two variables with the same name within the same scope or inside the enclosing scopes.
-We have violated this rule in this example we have a local variables which name is same as the instance variable a and b.

so what happens when we violate this rule

So if we violate something like this than what really happens is the instance variable gets hidden. see the example code again if we write something like
a=athan what does it really mean we are assigning the
values that is being passed to the method to the same variable.The compile gets confused since have the same name .So we need to tell the compiler that this value has to be assigned to the instance variable of the current class since it has the same name as the
local variable .

What can be the next solution

The simple solution can be eliminating the use of same variable names inside the same scope but some programmer believes it as a good practice.

About tarasj

hi friends i to blog what i have learned .lets talk and share
This entry was posted in ..BASIC.. and tagged . Bookmark the permalink.