java this的用法

/**

* 测试this的用法

*/

public class TestThis {

int a,b,c;

TestThis(){

System.out.println("当前对象为:"+this);

//this指向调用构造方法进行初始化的对象

}

TestThis(int a,int b){

this();

//这里的this()指代 TestThis()构造方法

//使用this调用构造方法必须要放在第一行

this.a = a;

this.b = b;

}

TestThis(int a,int d,int c){

this(a,d);

//this的ad是(a,d,c)里的ad 不是(int a,int b)的形参ab

//使用this调用构造方法必须放第一行

this.c = c;

}

void print(int c){

System.out.println(this.c);

this.c = c;

//this指向当前调用print方法的对象

//因为print方法定义了int c 所以不带this.的c都判定为print的形参c

}

void print1(int b,int c){

this.b = b;

System.out.println(this.b);

this.print(c);

//this指向当前对象 可以省略this. 不同于this()调用构造方法

}

public static void main(String[] args) {

TestThis t1 = new TestThis(3,4,5);

t1.print1(6,7);

}

//this不能用在static方法内

}

java   this
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章