java中this的n种使用方法

2025-05-29 0 58

 this可能是几乎所有有一点面向对象思想的语言都会引用到的变量,java自然不例外。只是,this有多少种用法,我也不知道了,让我们来see see。

由简入奢! 易。

来个例子说明下:

?

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

57

58

59

60

61

62

63

64

65

66
public class debugertest {

public static void main(string[] args) {

userexample samp1 = new userexample("amy");

system.out.println("who are u? ");

system.out.println(samp1.whoareu());

system.out.println("intro yourself?");

system.out.println(samp1.introyourself());

}

}

class userexample {

private string name;

private integer age;

private mydoll mydoll;

public userexample() {

this(null);

}

// 3. 调用本类的其他构造方法

public userexample(string name) {

this(name, -1);

}

public userexample(string name, integer age) {

this.name = name;

this.age = age;

this.mydoll = new mydoll("prize");

}

// 2. 调用本类属性

public void changemyname(string name) {

this.name = name;

}

public void changemyage(integer age) {

this.age = age;

}

public string whoareu() {

return "i am " + name + ". ";

}

public string haooldareu() {

return "i am " + age + " old.";

}

// 1. 调用本类方法

public string introyourself() {

return this.whoareu() +

this.haooldareu() +

"\\r\\n whoami@ " + this.mydoll.whoami() +

"\\r\\n whoaresuper@ " + this.mydoll.whoaresuper();

}

class mydoll {

private string name;

public mydoll(string name) {

this.name = name;

}

public void changemyname(string name) {

this.name = name;

}

// 5. 隐藏式的调用

public string whoami() {

return whoareu();

}

public string whoareu() {

return "i am a doll, my name is " + name + ". ";

}

// 4. 调用父类的或指定的其他的类的同名方法

public string whoaresuper() {

return "super is " + userexample.this.whoareu() + ". ";

}

}

}

1. 调用本类方法,表达更清晰

?

1

2

3
public string introyourself() {

return this.whoareu() + this.haooldareu();

}

2. 调用本类属性,基本功亮出来

?

1

2

3
public void changemyname(string name) {

this.name = name;

}

3. 调用本类的其他构造方法,更灵活

?

1

2

3
public userexample(string name) {

this(name, -1);

}

4. 调用父类的或指定的其他的类的同名方法,为避免歧义而生的方法

?

1

2

3
public string whoaresuper() {

return "super is " + userexample.this.whoareu() + ". ";

}

5. 隐藏式的调用,为了写代码方便(更常用),不指定范围,java会在全类范围内向上查找变量或方法

?

1

2

3
public string whoami() {

return whoareu();

}

以上样例输出结果如下所示:

java中this的n种使用方法

  this是个基本的关键字,我们平时也一直在用,只是也不一定所有同学都清楚怎么用。

总结

以上所述是小编给大家介绍的java中this的n种使用方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!

原文链接:https://www.cnblogs.com/yougewe/p/9468960.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java中this的n种使用方法 https://www.kuaiidc.com/111474.html

相关文章

发表评论
暂无评论