使用关键字“this"在 Java 中 [英] Using the keyword "this" in java
问题描述
我试图了解 java 关键字 this
的实际作用.我一直在阅读 Sun 的文档,但我仍然对 this
的实际作用感到模糊.
I'm trying to get an understanding of what the the java keyword this
actually does.
I've been reading Sun's documentation but I'm still fuzzy on what this
actually does.
推荐答案
this
关键字是对当前对象的引用.
The this
keyword is a reference to the current object.
class Foo
{
private int bar;
public Foo(int bar)
{
// the "this" keyword allows you to specify that
// you mean "this type" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// "bar" and the parameter "bar" passed into the
// constructor
this.bar = bar;
}
}
另一种思考方式是,this
关键字就像您用来指代自己的人称代词.其他语言对同一概念有不同的词.VB 使用 Me
并且 Python 约定(因为 Python 不使用关键字,只是每个方法的隐式参数)是使用 self
.
Another way to think about it is that the this
keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me
and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self
.
如果您要引用本质上属于您的对象,您会这样说:
If you were to reference objects that are intrinsically yours you would say something like this:
我的手臂或我的腿
将this
视为一种类型说我的"的方式.因此,伪代码表示如下所示:
Think of this
as just a way for a type to say "my". So a psuedocode representation would look like this:
class Foo
{
private int bar;
public Foo(int bar)
{
my.bar = bar;
}
}
这篇关于使用关键字“this"在 Java 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!