THIS Keyword in Java:-
this is a Keyword which refers to current invoking Object. this keyword is used to access the instance
variable and instance methods. a keyword cannot be used within the static context.
- I.e.., this keyword cannot be written within a static method or static block.
There are some various usages of 'THIS' keyword in Java are as follows:-
- It can be used to invoke or initiate a current class constructor.
- It can be passed as an argument in the method calling.
- It can be passed as an argument in the constructor call.
- It can be used to return the current class instance.
â—¾Examples (1) :
â—¾Examples (2):
1: public class Animal {
2: void makeNoise() {
3: System.out.println(this);
4: }
5: public static void main(String[] args) {
6: Animal an=new Animal();
7: System.out.println(an);
8: an.makeNoise();
9: }
10: }
Before Compilation of program lets's understand the Structure of Our Program Line by Line:-
- Class: class Animal.
- Creating Method: make noise.
- Creating the Main Method.
- Creating an Object Of Animal.
- Calling or invoking make noise method with the help of object reference (an).
Let's compile and run the code
public class Person {
String name="Tom";
void eat() {
this.washHands();//(washHands) Method Calling
this.serveFood();//(serveFood) Method Calling
System.out.println("Tom eat food");
this.washHands();//again (washHands) Method Calling
}
void washHands() {
System.out.println("Tom Wash your hands");
}
void serveFood() {
System.out.println("Tom Serve food");
}
public static void main(String[] args) {
Person pe=new Person();
pe.eat(); // Method Calling or invoking
}
}
Let's compile and run the code
â—¾Examples (3): public class Product {
int price=20;
void printProductDetails() {
System.out.println("Product price ="+this.price+" "+"bucks");
}
public static void main(String[] args) {
Product pro=new Product();
pro.printProductDetails();
}
}
Let's compile and run the code
0 Comments