我一直在从Java 2:完整引用,第五版学习Java。我无法理解确切的目的this
关键字和实例变量隐藏的概念。请举例说明。
最佳答案
这样做的确切目的是消除字段变量中局部变量的歧义。
this 是实例内当前实例的别名或名称。它对于消除实例变量与局部变量(包括参数)的歧义很有用,但它本身可以用来简单地引用成员变量和方法,调用其他构造函数重载,或者简单地引用实例。适用用途的一些示例(并非详尽无遗):
class Foo
{
private int bar;
public Foo() {
this(42); // invoke parameterized constructor
}
public Foo(int bar) {
this.bar = bar; // disambiguate
}
public void frob() {
this.baz(); // used "just because"
}
private void baz() {
System.out.println("whatever");
}
}
另请阅读this keyword还有this链接
关于java - 讲解java中 "this"关键字的作用以及使用 "this"关键字隐藏实例变量的概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20857771/