this keyword in Java. If you want to get knowledge and clear understanding about Java this keyword. Then its a best place for you, here i will teach
you in detail about Java this keyword with very easy to understand examples.
What is this keyword in Java?
In Java, this keyword can be
used in different manners. It can be used to mention class instance variables.
To explain it in detail, lets take an example.
Suppose we have a class
having one instance variable x and inside this class, we have a constructor
that accept one parameter and if variable name for the parameter of constructor
is exactly same as class variable, than this will create issue for Java because
of ambiguity
Example Program
class ThisExp
{
int x;
ThisExp (int x)
{
x = x;
}
public void show ()
{
System.out.println (x); //here we have problem because Class
variable name and constructor parameter variable name is same
}
}
public class B
{
Public static void main (String ar[ ])
{
ThisExp obj = new ThisExp(100);
Obj.show();
}
}
We will get error in the
result because class variable x is assigned to constructor parameter which has
exactly same name.
Now to solve this problem,
we can use “this” keyword in Java
Example Program
class ThisExp
{
int x;
ThisExp (int x)
{
this.x = x;
}
Public void show ()
{
System.out.println (x); }
}
Public class B
{
Public static void main (String ar[ ])
{
ThisExp obj = new ThisExp(100);
Obj.show();
}
}
Now we will get result without
any error because local variable and instance variables are distinguished using
this keyword which will help us to identify the class instance variable and
local variable.
When class instance variable
and local variable names are different, than there is no need to use this
keyword
Example Program without this
keyword
class ThisExp
{
int x;
ThisExp (int y)
{
x = y;
}
public void show ()
{
System.out.println (x);
}
}
public class B
{
public static void main (String ar[ ])
{
ThisExp obj = new ThisExp(100);
obj.show();
}
}
In the above example, we have no need to use
Java this keyword because in this example, class instance variable and local
variable are both different.
Java this keyword can also be
used to call class method, but its optional because if we don’t write
this keyword to call the current class method, compiler will put it by itself.
class First
{
public void a()
{
System.out.println(“method a”);
}
public void b()
{
System.out.println(“method b”);
this.a();
}
}
We can also call current
class constructor using this()
For Example
class Test
{
Test() //constructor
{
System.out.println(“I am constructor”);
}
Test(int x) //constructor with one argument
{
this(); //calling constructor
System.out.println(x);
}
}
class Test2
{
public static void main (String a[])
{
Test obj = new Test (3);
}
}
Output will be
I am constructor
3

No comments:
Post a Comment