Hello friends how are you, today in this blog i will teach you what is this keyword, in how many ways this keyword can be used, how this keyword works and many programs using this keyword in a very simple way.
Let's start
2.It can be used to replace local variable with class level variable.
3.It is also used to call current class method/function.
4.It is also used to call current class overloaded constructor.
1. this keyword as a variable hiding
By using this keyword we can replace local variable with instance variable. For better understanding see the below example.
class Rectangle
{
//declaring instance variable
int height=10,width=20;
public void area()
{
//declaring local variable
int height=5,width=6,ar;
//using local variable
ar=height*width;
System.out.println("Area 1="+ar);
//using class level(instance) variable
ar=this.height*this.width;
System.out.println("Area 2="+ar);
}
}
class Easy
{
public static void main(String[] args)
{
//Creating instance(object) of class
Rectangle obj=new Rectangle();
//calling class function
obj.area();
}
}
/*
### Output ###
Area 1=30
Area 2=200
*/
2. this keyword with function
By using this keyword we can also call a function of class without creating instance(object) of that class. For better understanding see the below example.
class Geometry
{
public void rectangle_area(int height,int width)
{
int ar=height*width;
System.out.println("Area of rectangle="+ar);
}
public void square_area(int side)
{
int ar=side*side;
System.out.println("Area of square="+ar);
//calling function using this keyword
this.rectangle_area(12, 13);
}
}
class Easy
{
public static void main(String[] args)
{
//Creating instance(object) of class
Geometry obj=new Geometry();
//calling class function
obj.square_area(12);
}
}
/*
### Output ###
Area of square=144
Area of rectangle=156
*/
3. this keyword constructor
By using this keyword we can also call a function of class without creating instance(object) of that class. For better understanding see the below example.
class Rectangle
{
//parameterised constructor
Rectangle(int height,int width)
{
int ar=height*width;
System.out.println("Area of rectangle="+ar);
}
//default constructor
public Rectangle()
{
//calling parameterised constructor
this(12,13);
System.out.println("I am inside default constructor");
}
}
class Easy
{
public static void main(String[] args)
{
//Creating instance(object) of class
Rectangle obj=new Rectangle();
}
}
/*
### Output ###
Area of rectangle=156
I am inside default constructor
*/
Request:-If you found this post helpful then let me know by your comment and share it with your friend.
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all.
If you have not subscribed my website then please subscribe my website.
Try to learn something new and teach something new to other.
Thanks.😊
0 Comments