转帖this的用法方便自己以后查看
必须用this关键字的三种情况:
1、我们想通过构造方法将外部传入的参数赋值给类的成员变量,构造方法的形式参数名称与类的成员变量名相同。例如:
class Person
...{
String name;
public Person(String name)
...{
this.name = name;
}
}
class Container
...{
Component comp;
public void addComponent()
...{
comp = new Component(this);
}
}
class Component
...{
Container myContainer;
public Component(Container c)
...{
myContainer = c;
}
}
public class Person
...{
String name;
int age;
public Person(String name)
...{
this.name = name;
}
public Person(String name,int age)
...{
this(name);
this.age = age;
}
}
1.this可指代对象自己本身: 当在一个类中要明确指出使用对象自己的属性或方法时就应该加上this引用,如下例 子:
输出的结果为: Maybe=love you
this.Maybe=love
this.Maybe=love you
第一行直接对构造函数中传递过来的参数Maybe进行输出,第二行是对成员变量(属性) Maybe的输出,第三行是先对成员变量(属性)Maybe赋值后进行输出。
2.在一个构造函数中调用另一个构造函数时,用this关键字:
以下例子:

public class Flower...{ 
private int petalCount=0; 
private String s=new String("null"); 

public Flower(int petals)...{ 
petalCount=petals; 
} 

public Flower(String ss)...{ 
s=ss; 
} 

public Flower(String s,int petals)...{
this(petals); //java中在一个构造函数中可以调用一次其他的构造函数,并且这条语句 必须在这个构造函数的第一行 
this.s=s; 
} 
}

public class love...{
String Maybe="love"; 

public love(String Maybe)...{ 
System.out.println("Maybe=" + Maybe); 
System.out.println("this.Maybe="+this.Maybe); 
this.Maybe=Maybe; 
System.out.println("this.Maybe="+this.Maybe); 
} 

public static void main(String[] args)...{ 
love s=new love("love you"); 
} 
} 

839

被折叠的 条评论
为什么被折叠?



