首页 > 技术文章 > Java this关键字使用 详解+ 证明

Bytezero 2021-09-15 19:39 原文

  1 package com.bytezero.thistest;
  2 /**
  3  * 
  4  * @Description 
  5  * @author  Bytezero·zhenglei!      Email:420498246@qq.com
  6  * @version
  7  * @date 2021年9月15日下午7:38:02
  8  * @
  9  *
 10  */
 11 /*
 12  * this关键字使用
 13  * 1.this可以用来修饰属性,方法,构造器
 14  * 
 15  * 2.this修饰属性和方法
 16  *   this理解为当前对象  或 当前正在创建的对象
 17  * 
 18  *   (1)在类的方法中,可以使用“this.属性”或“this.方法”的方式,调用当前对象属性
 19  * 或方法, 但是,通常情况下,我们都选择省略了“this.",特殊情况下,如果方法
 20  * 的形参和类的属性重名,我们必须显示式的使用“this.变量”的方式,表明此变量是
 21  * 属性,而非形参.
 22  * 
 23  *   (2)在类的构造器中,可以使用“this.属性”或“this.方法”的方式,调用当前正在创建的
 24  * 对象属性或方法, 但是,通常情况下,我们都选择省略了“this.",特殊情况下,如果构造器
 25  * 的形参和类的属性重名,我们必须显示式的使用“this.变量”的方式,表明此变量是
 26  * 属性,而非形参.
 27  * 
 28  *  3. this调用构造器
 29  *   (1) 我们在类的构造器中,可以显示的使用“this(形参列表)”方式,调用本类中的指定的其他
 30  * 构造器  
 31  *   (2)构造器不能通过“this(形参列表)”方式调用自己
 32  *   (3)如果一个类中有n个构造器,则最多有n - 1个构造器中使用了“this(形参列表)”
 33  *   (4)规定:this(形参列表)  必须声明当前构造器的首行
 34  *   (5)构造器内部,最多只能声明一个 this(形参列表),用来调用其他的构造器
 35  *   
 36  *   
 37  * 
 38  */
 39 public class PersonTest
 40 {
 41     public static void main(String[] args) 
 42     {
 43         Person p1 = new Person();
 44         
 45         p1.setAge(2);
 46         System.out.println(p1.getAge());
 47         
 48         p1.eat();
 49         
 50         Person p2 = new Person("Tom");
 51         System.out.println(p2.getName());
 52         
 53     }
 54 }
 55 
 56 
 57 class Person
 58 {
 59     private String name;
 60     private int age;
 61     
 62     
 63     //1
 64     public Person()
 65     {
 66         this.eat();
 67         String info = "已经被调用()";
 68         System.out.println(info);
 69     }
 70     
 71     //当前正在创建的对象
 72     public Person(String name)
 73     {
 74         this(); //1 调了 1 这个构造器
 75         this.name = name;
 76     }
 77     
 78     public Person(int age)
 79     {
 80         this();
 81         this.age = age;
 82     }
 83     
 84     
 85     public Person(int age,String name)
 86     {
 87         this(age);
 88         //this.age = age;
 89         this.name = name;
 90     }
 91 
 92     
 93     
 94     
 95     public void setName(String name)
 96     {
 97         this.name = name;
 98     }
 99     
100     public String getName()
101     {
102         return this.name;
103     }
104     
105     
106     
107     public void setAge(int age)
108     {
109         this.age = age;
110     }
111     
112     public int getAge()
113     {
114         return this.age;
115     }
116     
117     
118     public void eat()
119     {
120         System.out.println("人吃饭");
121         this.study();
122     }
123     public void study()
124     {
125         System.out.println("人学习");
126     }
127     
128     
129     
130     
131     
132     
133     
134     
135 }

 

推荐阅读