Jak przypisuje się wartość „tego” w różnych scenariuszach | Za 2 minuty
Zastosowanie tego słowa kluczowego
- Służy do odwoływania się do zmiennej instancji bieżącej klasy.
- Służy do wywoływania domyślnego konstruktora bieżącej klasy.
- Służy do wywoływania metody bieżącej klasy.
- Służy do zwracania bieżącej instancji Java.
1. Używany do odwoływania się do zmiennej instancji bieżącej klasy.
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. Służy do wywoływania domyślnego konstruktora bieżącej klasy
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. Służy do wywoływania metod bieżącej klasy
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. Służy do zwracania bieżącej instancji 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.Udowodnienie tego słowa kluczowego
Tutaj drukujemy ten sam wynik zmiennej referencyjnej i to
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
Dziękujemy za poświęcenie nam swoich cennych 2 minut. Zachęcamy do dyskusji na DM.
Poczta: [email protected]
GitHub: https://github.com/WamanBirajdar