【发布时间】:2014-09-27 15:22:03
【问题描述】:
我一直在使用多种方法,但我的“java 完整参考”一书没有很好地解释如何使用“this”关键字。
【问题讨论】:
-
如果完整参考没有解释
this,我会感到惊讶。 -
它是用于构造函数的,对吗?用的很好 2 知道 this , * ahem *
我一直在使用多种方法,但我的“java 完整参考”一书没有很好地解释如何使用“this”关键字。
【问题讨论】:
this,我会感到惊讶。
java中的这个
用于在被调用的方法或构造函数中引用对象的数据成员,以防字段与局部变量发生名称冲突
public class Test {
String s;
int i;
public Test(String s, int i){
this.s = s;
this.i = i;
} }
它用于从同一个类的另一个构造函数中调用一个构造函数,也可以说是构造函数链接。
public class ConstructorChainingEg{
String s;
int i;
public ConstructorChainingEg(String s, int i){
this.s = s;
this.i = i;
System.out.println(s+" "+i);
}
public ConstructorChainingEg(){
this("abc",3); // from here call goes to parameterized constructor
}
public static void main(String[] args) {
ConstructorChainingEg m = new ConstructorChainingEg();
// call goes to default constructor
}
}
它还有助于方法链接
class Swapper{
int a,b;
public Swapper(int a,int b){
this.a=a;
this.b=b;
}
public Swapper swap() {
int c=this.a;
this.a=this.b;
this.b=c;
return this;
}
public static void main(String aa[]){
new Swapper(4,5).swap(); //method chaining
}
}
【讨论】:
main 方法中,您可以将Swapper 分配给一个变量(或做类似的事情),这样return this 行就有用处了。跨度>
这是一对:
public class Example {
private int a;
private int b;
// use it to differentiate between local and class variables
public Example(int a, int b) {
this.a = a;
this.b = b;
}
// use it to chain constructors
public Example() {
this(0, 0);
}
// revised answer:
public int getA() {
return this.a;
}
public int getB() {
return this.b
}
public int setA(int a) {
this.a = a
}
public void setB(int b) {
this.b = b;
}
}
this指的是属于使用this的对象的属性。例如:
Example ex1 = new Example(3,4);
Example ex2 = new Example(8,1);
在这些情况下,ex1.getA() 将返回 3,因为this 指的是属于名为ex1 的对象的a,而不是ex2 或其他任何东西。 ex2.getB() 也是如此。
如果您查看setA() 和setB() 方法,使用this 将属于对象的属性a 和b 与参数名称区分开来,因为它们是相同的。
【讨论】:
this 是对自身的引用