好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java中this的n种使用方法

  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();

   }

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

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

总结

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

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

查看更多关于java中this的n种使用方法的详细内容...

  阅读:39次