this:表示当前对象的指针 指向当前对象,表示对当前对象的调用 用途: 1、构造方法,当构造方法的名称跟类的成员变量的名称一样的时候,可以使用this代表当前对象 注意:当构造方法中需要其他构造方法时,可以使用this(参数列表)调用其他构造方法,但是需要位于方法体的第一行 2.普通方法中: 当多个普通方法需要互相调用时,可以使用this.方法来进行调用,指的是当前对象的其他方法 3、调用成员变量的时候如何使用: 当方法名的参数名称跟成员变量保持一致时,使用this.变量名称 表示的是对象的值,而使用变量名称则是参数的值 注意: this不能使用于static方法中 package com.gml; public class ThisDemo { //成员变量 String name; int age; int height; double weight; //构造器,构造方法 public ThisDemo() { } public ThisDemo(String name,int age,int height,double weight){ this.name=name; this.age=age; this.height=height; this.weight=weight; } public static void main(String[] args) { ThisDemo td = new ThisDemo("阿龙",18,170,110.5); System.out.println("姓名: "+td.name); System.out.println("年龄: "+td.age); System.out.println("身高: "+td.height); System.out.println("体重: "+td.weight); } }
package com.gml; public class TestThis { int a,b,c; TestThis(){ System.out.println("我好喜欢小顺子啊! "); } TestThis(int a,int b){ this();//调用无参的构造方法,并且必须位于第一行! a=a;//这里都是指的局部变量而不是成员变量 this.a = a;//这样就区分了成员变量和局部变量,这种情况占了this使用情况的大多数! this.b = b; } TestThis(int a,int b,int c){ this(a,b);//调用无参的构造方法,并且必须位于第一行! this.c =c; } void sing(){ } void chifan(){ this.sing();//sing(); System.out.println("小顺子喊你回家吃饭! "); } public static void main(String[] args) { TestThis hi = new TestThis(2,3); hi.chifan(); } }