this关键字主要有三个应用:
调用属性(代码示例):
1 | public class thisDemo01 { |
调用方法(普通方法与构造方法)
调用普通方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25public class thisDemo01 {
public static void main(String[] args) throws Exception {
BlueMoon bm = new BlueMoon("渣渣辉", 100);
System.out.println(bm.getInfo());
}
}
class BlueMoon {
private String name;
private int level;
public BlueMoon(String name, int level) {
this.name = name;
this.level = level;
}
public void print() {
System.out.println("************************");
}
public String getInfo() {
this.print();//调用普通方法
return "大家好!我是" + this.name + ",我是贪玩蓝月的战士,等级:" + this.level;
}
}调用构造方法:
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
48public class thisDemo01 {
public static void main(String[] args) throws Exception {
BlueMoon bm1 = new BlueMoon();
BlueMoon bm2 = new BlueMoon("古天乐");
BlueMoon bm3 = new BlueMoon("小志传奇", "陈赫", "法师");
System.out.println(bm1.getInfo());
System.out.println(bm2.getInfo());
System.out.println(bm3.getInfo());
}
}
class BlueMoon {
private String game;
private String name;
private String title;
private int level;
public BlueMoon() {
this("贪玩蓝月", "无名氏", "未定", 0);
}
public BlueMoon(String name) {
this("贪玩蓝月", name, "剑士", 90);
}
public BlueMoon(String game, String name) {
this(game, name, "战士", 100);
}
public BlueMoon(String game, String name, String title) {
this();
this.game = game;
this.name = name;
this.title = title;
}
public BlueMoon(String game, String name, String title, int level) {
this.game = game;
this.name = name;
this.title = title;
this.level = level;
}
public String getInfo() {
return "欢迎来到" + this.game + "!我是" + this.name + ",职业:" + this.title + ",等级:" + this.level + "级";
}
}
当前对象调用:
1 |
|
参考文献
https://blog.csdn.net/yanwenwennihao/article/details/79375611
https://blog.csdn.net/ikv1989/article/details/79182432