this 在 java 中是一个关键字, 翻译为 这个;
this 在 java 中可以是引用,可以是变量,当为变量时,变量中保存的内存地址指向自身,this 存储在 JVM 堆内存 java 对象内部
1、this 关键字的第一种作用是当构造函数进行参数传递时,局部变量与成员变量重名时,为赋值时能将局部变量的值传给实例变量,在实例变量上加 this [ 语法格式:this. ];
2、this 关键字可以出现在“”实例方法“”当中,this 指向当前正在执行这个动作的对象(this 代表当前对象);
1 public class Test19 { 2 3 // 属性 4 String name; 5 6 String interest; 7 8 public static void main(String[] args) { 9 10 // 创建对象 11 Test19 t = new Test19("程俭","play games" ); 12 13 // this.Test(); 14 // 使用 this 出错; 15 // 因为 this 在静态方法中不能使用,所以在静态方法中只能通过 “ 引用 . ” 的方式进行调用 16 17 t.Test(); 18 19 } 20 21 22 // 创建一个构造方法 23 public Test19() { 24 25 } 26 27 28 // 有参数构造方法 29 public Test19(String name, String interest) { // 此处的参数名与属性中的成员变量名重名,但是这样语法是正确的 30 31 this.name = name; 32 // 在构造方法中这样进行对成员变量赋值是错误的,这两个 name 在 JVM 看来根本就没有一个是成员变量 33 // 所以这个时候 this 关键字的作用就在该对象中指定自己及自己所拥有的属性 34 this.interest = interest; 35 // this 关键字在指向实例变量的时候要使用 “ this. ” 的方法去调用属性 36 37 } 38 39 // 创建一个普通方法 40 public void Test() { 41 System.out.println("我被 this 指向了"); 42 } 43 44 public void Test_Test() { 45 System.out.println("我被 this 指向了"); 46 47 Test(); 48 // 奇妙的事情发生了,在普通方法中调用另一个方法可以不用 引用. 的方式调用,可以直接类名的方式调用 49 // 原因是在调用该方法时,有一个 this. 在调用该方法,不过 this 可以省略 50 this.Test(); 51 } 52 }
3、 this 关键字可以使用在构造方法中,通过当前的构造方法调用其它的构造方法[ 语法格式:this() ];
1 public class Test20 { 2 3 // 属性 4 String year; 5 String month; 6 String day; 7 8 public static void main(String[] args) { 9 10 Test20 t = new Test20(); 11 new Test20("2020","4","9"); 12 13 } 14 15 // 创建一个有参构造方法 16 public Test20(String year, String month, String day) { 17 18 this.year = year; 19 this.month = month; 20 this.day = day; 21 System.out.println(year + "-" + month + "-" + day); 22 } 23 24 public Test20() { 25 // this() 的作用是在一个构造方法中去调用另一个构造方法 26 this("1970","1","1"); 27 28 // 但是有一个重点要记住: this() 只能放在方法体中的句首,如果它前面有任何的代码,那么 this() 都不会有效 29 } 30 }
this 关键字在普通方法中可以调用属性和其他方法,不过在调用的过程中可以省略 this.;
this 关键字在静态方法中不能使用,调用其他方法和调用属性都不行;
1 public class Test21 { 2 3 public static void main(String[] args) { 4 5 // 创建对象 6 Test21 t = new Test21(); 7 8 // 对普通方法的调用:引用 . 的方式去调用 9 t.Test_e(); 10 11 // 对静态方法的调用: 类名. 的方式调用,但大多情况下可以省略 类名. 12 // Test21.Test_t(); √ 13 Test_t(); 14 } 15 16 17 // 创建一个普通方法 18 public void Test_e() { 19 20 System.out.println("我是普通方法哦"); 21 22 // 在普通方法中调用静态方法 23 // Test21 t = new Test21(); 24 // t.Test_t(); 25 26 // 可以使用 this. 的方式调用静态方法 27 this.Test_t(); // 当然此处的 this. 也可以省略 28 29 } 30 31 // 创建一个静态方法 32 public static void Test_t() { 33 34 System.out.println("我是静态方法哦"); 35 36 } 37 }
原文:https://www.cnblogs.com/evething-begins-with-choice/p/12658634.html