Java面向对象之关键字this 入门实例

一、基础概念

  1.关键字this是指:哪个对象调用this所在的函数。this就指向当前这个对象。

  2.用法:

    (1).this关键字可以解决:构造函数私有化问题。

        注意:构造函数只能被构造函数调用,不能直接被一般方法调用。

    (2).this关键字可以用于构造函数间的调用,可以访问本类中的其他构造函数。是为了初始化的复用。  

        注意:必须定义在构造函数的第一行!

           不要出现互相调用,产生递归,容易栈溢出。

    (3).this关键字用来区分局部变量和成员变量同名的情况。

        注意:this关键字标识的成员变量。

二、代码实例 

 1 class Person
 2 {
 3     private String name;
 4     private int age;
 5     
 6     private Person()//构造函数私有化
 7     {
 8         System.out.println("新对象实例化") ;//被构造函数调用的构造函数语句
 9     }
10     
11     Person(String n)
12     {
13         this();// 调用本类中的调用构造函数语句。
14         name = n;
15     }
16     
17     Person(String name,int age)
18     {
19         this(name);//调用本类中的调用构造函数语句。
20         this.age = age;//this标识的成员变量。
21     }
22     
23     public void show1()
24     {
25         System.out.println("name="+name);
26     }
27     
28     public void show2()
29     {
30         System.out.println("name="+name+",age"+age);
31     }
32     
33     //传递一个Person对象,判断是否是同龄人。
34     public boolean equalsAge(Person pp)
35     {
36         return this.age == pp.age;
37     }
38 }
39 
40 class ThisDemo
41 {
42     public static void main(String[] args) 
43     {
44 
45         Person p1 = new Person("xiaoming");
46         p1.show1();
47         Person p2 = new Person("xiaofang",20);
48         p2.show2();
49         Person p3 = new Person("xiaohong",21);
50         p3.show2();
51         
52         //输出p3、p4是否为同龄人
53         boolean b = p2.equalsAge(p3);
54         System.out.println("Whether or not the age is equal:  "+b);
55     }
56     
57 }

三、代码运行

  

 

 

posted @ 2018-04-13 22:10  竹小冉  阅读(589)  评论(0编辑  收藏  举报