日期:2014-05-20  浏览次数:20709 次

关于this关键字,一直不理解,希望大家帮忙指点下。
如题,
this关键字在不同的地方,
都分别表示什么啊、?
这个问题一直搞不清楚,
大家帮忙解释下,
谢谢

------解决方案--------------------
this 是指当前对象 呵呵 如
你类里面的属性 this.proprtey = proprtey ;
意思就是你传参的属性赋值给类里的属性;
------解决方案--------------------
使用this调用本类中的属性

现在观察以下代码,看会有那些问题:

public void setName(String name){

name = name ;



这里面的两个name都是setName方法中的name参数。

此时,特别希望可以通过一个指定的标识明确的表示要把传入的name参数的值给类中的属性,所以此时就需要使用this关键字,使用this.name就表示类中的属性。

class Person{

private String name ;

private int age ;

public Person(String name,int age){

this.setName(name) ;

this.setAge(age) ;

}

public void setName(String name){

this.name = name ;

}

public void setAge(int age){

this.age = age ;

}

public String getName(){

return this.name ;

}

public int getAge(){

return this.age ;

}

public void print(){

System.out.println("姓名:"+this.name+",年龄:"+this.age) ;

}

};

public class Demo35{

public static void main(String args[]){

Person p1 = new Person("张三",30) ;

p1.print() ;

}

}; 

使用this还可以从一个构造方法中调用其他构造方法。

例如:有以下一个要求,一个类中存在了三个构造方法,但是要求, 不管怎么调用,最终都要求可以在对象实例化的时候打印一个“新的对象产生了”的提示。

class Person{

private String name ;

private int age ;

public Person(){

System.out.println("新的对象产生了。。。") ;

}

public Person(String name){

System.out.println("新的对象产生了。。。") ;

this.setName(name) ;

}

public Person(String name,int age){

System.out.println("新的对象产生了。。。") ;

this.setName(name) ;

this.setAge(age) ;

}

public void setName(String name){

this.name = name ;

}

public void setAge(int age){

this.age = age ;

}

public String getName(){

return this.name ;

}

public int getAge(){

return this.age ;

}

public void print(){

System.out.println("姓名:"+this.name+",年龄:"+this.age) ;

}

}; 

以上代码虽然可以实现功能,但是同样的代码出现了三次,而且后面的两次出现纯属多余吧。用this()的形式可以调用类中的无参构造方法。

class Person{

private String name ;

private int age ;

public Person(){

System.out.println("新的对象产生了。。。") ;

}

public Person(String name){

// 最终都是调用无参构造方法

this() ;

this.setName(name) ;

}

public Person(String name,int age){

this(name) ;

this.setAge(age) ;

}

public void setName(String name){

this.name = name ;

}

public void setAge(int age){

this.age = age ;

}

public String getName(){

return this.name ;

}

public int getAge(){

return this.age ;

}

public void print(){

System.out.println("姓名:"+this.name+",年龄:"+this.age) ;

}

};

public class Demo36{

public static void main(String args[]){

Person p1 = new Person("张三",30) ;

p1.print() ;

}

}; 

注意点1:

如果使用了this调用其他构造方法,则此语句,必须写在构造方法的首行。

public void fun(){

// 发现在调用fun方法的时候,必须先设置name的值

this("zhangsan") ;



public Person(String name,int age){

this.setAge(age) ;

this(name) ; //--> 必须放在首行