-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththis keyword.txt
56 lines (44 loc) · 1.84 KB
/
this keyword.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
This keyword:
If you many constructors you want to call the specific or current constructor then you use the this keyword.
Example:
public class Person {
private String name;
private int age;
// Constructor with parameters
public Person(String name, int age) {
this.name = name; // "this.name" refers to the instance variable, "name" refers to the parameter
this.age = age; // "this.age" refers to the instance variable, "age" refers to the parameter
}
// Method to display information about the person
public void displayInfo() {
System.out.println("Name: " + this.name); // Using "this.name" to refer to the instance variable
System.out.println("Age: " + this.age); // Using "this.age" to refer to the instance variable
}
// Getter and setter methods
public String getName() {
return this.name; // Using "this.name" to refer to the instance variable
}
public void setName(String name) {
this.name = name; // Using "this.name" to refer to the instance variable
}
public int getAge() {
return this.age; // Using "this.age" to refer to the instance variable
}
public void setAge(int age) {
this.age = age; // Using "this.age" to refer to the instance variable
}
}
public class Main {
public static void main(String[] args) {
// Creating an instance of Person class
Person person1 = new Person("John", 30);
// Displaying information about the person
person1.displayInfo();
// Changing the person's name using setter method
person1.setName("Alice");
// Changing the person's age using setter method
person1.setAge(25);
// Displaying updated information about the person
person1.displayInfo();
}
}