this关键字简单应用

 1 class PersonDemo3 
 2 {
 3     public static void main(String[] args) 
 4     {
 5         Person p=new Person("张三",22);
 6     }
 7 }
 8 
 9 /*
10 this 语句
11 1.用于构造函数间互相调用时使用,不能在一般函数中调用
12 2.this语句在构造函数中必须是第一句,并且在一个构造函数中只能使用一次
13 */
14 //this关键字表示this所在函数所在的对象,用于标记对象的成员,避免出现歧义和出错,方便阅读
15 class Person
16 {
17     private int age;
18     private String name;
19     Person() //无参构造函数
20     {
21         System.out.println("A: name:"+this.name+","+"age:"+this.age);
22         
23     }
24     Person(String name) //一个参数构造函数
25     {
26         this.name=name;
27         //System.out.println("B: name:"+this.name+","+"age:"+this.age);
28         
29     }
30     Person(String name,int age)  //两个参数构造函数
31     {
32         //this.name=name;
33         this(name);//使用this语句调用构造函数
34         this.age=age;
35         System.out.println("C: name:"+this.name+","+"age:"+this.age);
36         
37     }
38 }

输出结果:

C: name:张三,age:22

原文地址:https://www.cnblogs.com/sunshine6/p/5850246.html