-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThisKeyword.java
43 lines (30 loc) · 992 Bytes
/
ThisKeyword.java
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
class Person {
String name;
int age;
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class ThisKeyword {
public static void main(String[] args) {
// this keyword is used to refer to current object
// it is used to avoid ambiguity when we have methods and variables with same name
// it is used to access non-static variables and methods of current object
// it is used to call constructor of same class
Person person = new Person();
Person person2 = new Person("Anupam", 22);
System.out.println(person.getName() + " : " + person.getAge());
System.out.println(person2.getName() + " : " + person2.getAge());
}
}