Как значение «this» присваивается в разных сценариях | через 2 мин.

Использование этого ключевого слова

  1. Используется для ссылки на текущую переменную экземпляра класса.
  2. Используется для вызова конструктора текущего класса по умолчанию.
  3. Используется для вызова текущего метода класса.
  4. Используется для возврата текущего экземпляра Java.

1. Используется для ссылки на текущую переменную экземпляра класса.

package this_keyword;

class Student{
 //instance variable 
 String name;
 int age;
 
 
 //Parameterized constructor
 Student(int age,String name)
 {
  this.name=name;
  this.age=age;
 }
 void display()
 {
  System.out.println(name+" "+age);
 }
}
public class This_keyword_example {

 public static void main(String[] args) {
  Student s= new Student(25,"waman");
  s.display();
 }

}


Ouput 
waman 25

2. Используется для вызова конструктора текущего класса по умолчанию

package this_keyword;

class Student1{
 
 String name;
 int age;
 //no parameterized constructor
 Student1()
 {
  System.out.println("This is defualt constructor");
 }
 
 //parameterized constructor
 Student1(int age,String name)
 {
  this();
  this.name=name;
  this.age=age;
 }
 void dislpay()
 {
  System.out.println("Name of student:" +name+"   Age: "+age);
 }
 
 
}
public class this_Example2 {

 public static void main(String[] args) {
  Student1 s=new Student1(25,"waman");
  s.dislpay();



 }

}
Output

This is defualt constructor
Name of student:waman   Age: 25

3. Используется для вызова методов текущего класса

package this_keyword;

class employee{
 void salary()
 {
  System.out.println("inside salary method");
 }
 void bonus()
 {
  this.salary();
  System.out.println("inside bonus method");
 }
}
public class this_Example3 {

 public static void main(String[] args) {
  
  employee e=new employee();
  e.bonus();
 }

}
Output

inside salary method
inside bonus method

4.Используется для возврата текущего экземпляра JAVA

package this_keyword;
class Example{
 
 Example getStudent()
 {
  return this;
 }
 
 void disp()
 {
  System.out.println("calling disp() method");
 }
}
public class this_Example4 {

 public static void main(String[] args) {
  
  new Example().getStudent().disp();;
  
 }

}
Output

calling disp() method

5.Подтверждение этого ключевого слова

Здесь мы печатаем тот же вывод ссылочной переменной, что и этот

class staff{
 
 void technical()
 {
  System.out.println(this);
 }
}

public class this_Example5 {

 public static void main(String[] args) {
  staff s=new staff();
  System.out.println(s);
  s.technical();

 }

}
Output

this_keyword.staff@12edcd21
this_keyword.staff@12edcd21

Спасибо, что уделили нам 2 минуты бесценного времени, не стесняйтесь обращаться к нам за любым обсуждением.

Почта: [email protected]

GitHub: https://github.com/WamanBirajdar

Linkedin: https://www.linkedin.com/in/waman-b-birajdar/