我想更好地理解单独使用this.field和字段引用类字段有什么区别,如
this.integerField = 5;和
integerField = 5;发布于 2012-10-30 08:03:52
this关键字是指当前的object。通常我们使用this.memberVariable来区分成员变量和局部变量
private int x=10;
public void m1(int x) {
sysout(this.x)//would print 10 member variable
sysout(x); //would print 5; local variable
}
public static void main(String..args) {
new classInst().m1(5);
}离开具体的问题,在Overloaded constructors中使用this
我们可以使用它来调用重载构造函数,如下所示:
public class ABC {
public ABC() {
this("example");to call overloadedconstructor
sysout("no args cons");
}
public ABC(String x){
sysout("one argscons")
}
}发布于 2012-10-30 08:07:11
使用this关键字可以消除成员变量和局部变量之间的歧义,例如函数参数:
public MyClass(int integerField) {
this.integerField = integerField;
}上面的代码片段将局部变量integerField的值赋给具有相同名称的类的成员变量。
一些商店采用编码标准,要求所有会员访问都必须符合this。这是有效的,但不必要;在不存在冲突的情况下,删除this不会更改程序的语义。
发布于 2012-10-30 08:07:52
当您在实例方法中时,可能需要指定引用变量的作用域。例如:
private int x;
public void method(int x) {
System.out.println("Method x : " + x);
System.out.println("Instance x : " + this.x);
}而在本例中,您有两个x变量,一个是局部方法变量,另一个是类变量。您可以使用this来区分这两者,以指定它。
有些人总是在使用类变量之前使用this。虽然这不是必需的,但它可以提高代码的可读性。
至于多态性,您可以将父类称为super。例如:
class A {
public int getValue() { return 1; }
}
class B extends A {
// override A.getValue()
public int getValue() { return 2; }
// return 1 from A.getValue()
// have we not used super, the method would have returned the same as this.getValue()
public int getParentValue() { return super.getValue(); }
}关键字this和super都取决于您使用它的作用域;它取决于您在运行时使用的实例(对象)。
https://stackoverflow.com/questions/13131410
复制相似问题