码迷,mamicode.com
首页 > 其他好文 > 详细

this

时间:2016-11-23 14:41:36      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:构造方法   代码   class   打印   style   中华   turn   stat   type   

特点:

  this表示当前对象。

     当前对象 ←→ 当前正在调用实例成员的对象

换言之:谁调用了方法,谁就是当前对象。

什么时候使用this关键字呢?

  方法间的相互调用;

  this.字段;

  构造器中相互调用,但是此时this([参数])必须写在构造方法第一行。

this不能用在static修饰的方法里和static修饰的代码块里;

 1 //狗类
 2 class Dog
 3 {
 4 
 5     private String type;//品种
 6 
 7     private String color;//颜色
 8 
 9     private int age;//年龄
10 
11 
12     public String getType()
13     {
14         return type;
15     }
16     public void setType(String type)
17     {    
18         //赋值操作,没有给类字段type赋值
19 
20         //this
21         this.type = type;
22     }
23 
24 
25     void show()
26     {
27         Dog d = new Dog();
28         d.type="萨摩耶";
29         this.say(d);
30 
31     }
32     
33     //static 代码块里面不能使用 this
34     void say(Dog d)
35     {
36         //System.out.println("--->"+d.getType());//打印:萨摩耶
37         System.out.println("--->"+ this.getType());//打印:萨摩耶
38     }
39 
40     void p()
41     {
42         //这里的type到底表示谁的品种?
43         //谁调用p方法,此时该方法里的this就是谁? 一般情况下,this可以省略
44         //方法里有一个和字段同名的局部变量时,不能省略this
45 
46         String type = "sss";
47         System.out.println(this.type);//表示访问对象(调用方法的对象)的type
48     }
49 
50 }
51 
52 class ThisDemo 
53 {    
54 
55     private static String name;
56     public static void main(String[] args) 
57     {
58         //System.out.println(this.name);//ERROR
59         /**
60             this:表示当前对象;
61                 谁调用方法谁就是当前对象
62         
63         */
64         Dog d = new Dog();
65         d.setType("中华田园犬");//此时d在调用setType()方法,那么setType方法里的this就表示 d
66 
67 
68 
69         Dog hasiq = new Dog();
70         hasiq.setType("小哈");//此时hasiq在调用setType()方法,那么setType方法里的this就表示 hasiq
71 
72         System.out.println(d.getType());
73 
74 
75         hasiq.show();
76     }
77 }

 

this

标签:构造方法   代码   class   打印   style   中华   turn   stat   type   

原文地址:http://www.cnblogs.com/WestVillagedevil/p/6093527.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!