A method argument can have the same name as one of the class's member variables. If this is the case, then the argument is said to hide the member variable. Arguments that hide member variables are often used in constructors to initialize a class. For example, take the following Circle class and its constructor: class Circle { int x, y, radius; public Circle(int x, int y, int radius) { . . . } }The Circle class has three member variables: x, y and radius. In addition, the constructor for the Circle class accepts three arguments each of which shares its name with the member variable for which the argument provides an initial value. The argument names hide the member variables. So using x, y or radius within the body of the constructor refers to the argument, not to the member variable. To access the member variable, you must reference it through this--the current object: class Circle { int x, y, radius; public Circle(int x, int y, int radius) { this.x = x; this.y = y; this.radius = radius; } }Names of method arguments cannot be the same as another argument name for the same method, the name of any variable local to the method, or the name of any parameter to a catch clause within the same method.
this指当前对象,简单的来说就是当前类的引用 比如 class A { String s;//local s public void b(String s){ this.s = s; } }这里,this.s指明了参数里(String s)传来的值付给了A的s即(local s)这里this就是指class Agood luck!
class XXX { int int_val; public XXX(int int_val) { this.inv_val = int_val; //因为这里int_val同名,用this就可以区分 } public XXX(int v,Object o) { inv_val = v; //因为这里编译器知道,不用写this就可以区分,当然写this也不会错 }}
this.extent 表示当前类下的一个成员extent;
右边的extent把它看成相应的为一个值(大概的讲), 赋值给当前类下的成员this.extent
实例就是这个类有一个实例的对象,为这个类分配了内存,
好了,this的用处来了,我们在调用每一个方法时,其实编译器为我们多加了一个参数、这就是this指针,我们自己写得方法虽然传过N值,但实际上传了N+1个值,多出来那一个就是this。。
用来指示对像!
int x, y, radius;
public Circle(int x, int y, int radius) {
. . .
}
}The Circle class has three member variables: x, y and radius. In addition, the constructor for the Circle class accepts three arguments each of which shares its name with the member variable for which the argument provides an initial value.
The argument names hide the member variables. So using x, y or radius within the body of the constructor refers to the argument, not to the member variable. To access the member variable, you must reference it through this--the current object: class Circle {
int x, y, radius;
public Circle(int x, int y, int radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
}Names of method arguments cannot be the same as another argument name for the same method, the name of any variable local to the method, or the name of any parameter to a catch clause within the same method.
比如
class A {
String s;//local s
public void b(String s){
this.s = s;
}
}这里,this.s指明了参数里(String s)传来的值付给了A的s即(local s)这里this就是指class Agood luck!
int int_val;
public XXX(int int_val) {
this.inv_val = int_val;
//因为这里int_val同名,用this就可以区分
}
public XXX(int v,Object o) {
inv_val = v;
//因为这里编译器知道,不用写this就可以区分,当然写this也不会错
}}