在Java构造函数中使用'this'关键字 [英] Using 'this' keyword in Java constructors

查看:403
本文介绍了在Java构造函数中使用'this'关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java中的这个关键字感到困惑。如果一个类有两个构造函数,并且我们在某个方法中使用 this 关键字,则使用 this 表示的对象将使用两个构造函数中的哪一个?

I am confused with the this keyword in Java. If a class has two constructors and we use the this keyword in some method, the object represented by this is instantiated using which of the two constructors?

推荐答案

你必须区分这个。 this(),可以这么说:

You have to distinguish between this. and this(), so to speak:

大多数情况下,你使用 this 作为对当前对象的引用,即在运行时为替换此对象的引用。例如,如果您使用作为参数或参考 this.someMember

Most of the time, you use this as the reference to the current object, i.e. the reference of this object is replaced at runtime for this. For instance, if you use this as parameter or reference this.someMember.

您可以使用具有不同参数的不同构造函数,即重载构造函数。在构造函数的开头,您可以使用 this(parameter_1,... parameter_n); 作为第一条指令来调用不同的构造函数。

You can have different constructors with different parameters, i.e. overload constructors. At the beginning of a constructor, you can call a different constructor by using this(parameter_1, ... parameter_n); as first instruction.

可以在找到对这两种情况的一个很好的解释。关于this关键字的java教程

这篇关于在Java构造函数中使用'this'关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆