疯狂java学习笔记之面向对象(四) - this关键字

Java中this关键字主要有以下两个方法:

  1、this引用 - 可用于任何非static修饰的方法和构造器中,当this用于方法中时,它代表调用该方法的实例/对象;当this用于构造器中时,它代表构造器正在初始化的实例/对象

  2、this调用 - 只能在构造器的第一行出现。

 

如何区分this引用与this调用呢?

  this引用写法为:this.  ;  而this调用写法为:this();

例1:

 1 class TestThis{
 2     private double weight;
 3     private String name;
 4 
 5     public TestThis(String name){
 6         //this引用在构造器中代表正在初始化的实例/对象
 7         this.name = name;
 8     }
 9 
10     public void info(){
11         System.out.println("这个是:" + name + ",重量为:" + this.weight);
12     }
13 
14     public void bat(){
15         //this引用在方法中代表谁并不明确,具体是由哪个对象调用它而决定的
16         this.weight = weight + 10;
17     }
18 
19     public static void main(String[] args){
20         TestThis tt = new TestThis("猴子");
21         tt.bat();//第一次调用bat方法,重量增加10
22         tt.info();//输出为:这个是:猴子,重量为:10.0
23         tt.bat();//第二次调用bat方法,重量在上一次的基础上再加10
24         tt.info(); //输出为:这个是:猴子,重量为20.0
25         TestThis tb = new TestThis("犊子");
26         tb.info();//因为tb没调用bat方法,所以它的重量依旧为0  输出为:这个是:犊子,重量为0.0
27     }
28 }

 

例2:

 1 public class TestThis1 {
 2     private String name; //封装后只能在当前类中访问
 3     private double weight;
 4     private int age;
 5     
 6     //构造器不需要声明返回值类型,若声明则会变为普通方法
 7     //构造器重载:类似方法重载-在同一个类中构造器名字相同,但形参不同
 8     public TestThis1(String name,int weight){
 9         this.name = name;
10         this.weight = weight;
11     }
12 
13     public TestThis1(String name,int weight,int age){
14         this(name,100);//this() - 调用当前类的另一个构造器(根据参数去匹配调用哪个构造器)
15         this.age = 5;
16     }
17 
18     public void info(){
19         System.out.println("这个是:" + name + ",重量为:" + weight + "KG,年龄是:" + age);
20     }
21 
22     public static void bat(String name){
23         this.name = name;
24     }
25 
26     public static void main(String[] args){
27         TestThis1 t1 = new TestThis1("小象",60);
28         t1.info();//调用方法的本质就是找到info()方法并执行方法内的语句块
29         TestThis1 t2 = new TestThis1("大象",200,3);
30         t2.info();
31     }
32 }

 

posted @ 2014-12-15 15:24  一世飛扬  阅读(190)  评论(0编辑  收藏  举报