Java - 何时使用“this"关键字 [英] Java - when to use 'this' keyword

查看:40
本文介绍了Java - 何时使用“this"关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中使用 this 关键字的最佳实践是什么?例如,我有以下课程:

What is the best practise for using the this keyword in Java? For example, I have the following class:

class Foo {
    Bar bar;

    public Foo(Bar bar) {
         this.bar = bar;
    }
}

这很好,但 Java 足够聪明,知道如果我将构造函数中的语句更改为

That's fine and all, but Java is clever enough to know what is happening if I change the statement in the constructor to

 bar = bar;

那么为什么要使用 this 关键字?(我意识到在某些情况下,完全有必要使用它,我只是要求这样的情况).实际上,我倾向于纯粹为了可读性而使用关键字,但通常的做法是什么?例如,在整个商店使用它会使我的代码看起来有点凌乱

So why use the this keyword? (I realise in some situations, it's totally necessary to use it, I'm just asking for situations like this). Actually, I tend to use the keyword purely for readability sake but what's the common practise? Using it all over the shop makes my code look a bit messy, for example

boolean baz;
int someIndex = 5;
this.baz = this.bar.getSomeNumber() == this.someBarArray[this.someIndex].getSomeNumber();

显然代码很差,但它说明了我的示例.在这些情况下,是否仅取决于个人喜好?

Obviously a poor bit of code but it illustrates my example. Is it just down to personal preference in these cases?

推荐答案

但是Java足够聪明,知道如果我将构造函数中的语句更改为

but Java is clever enough to know what is happening if I change the statement in the constructor to

  bar = bar;

假的!它可以编译,但它并没有像你想象的那样做!

FALSE! It compiles but it doesn't do what you think it does!

至于何时使用它,很多都是个人喜好.我喜欢在我的公共方法中使用 this,即使它是不必要的,因为那是接口发生的地方,并且很好地断言什么是我的,什么不是.

As to when to use it, a lot of it is personal preference. I like to use this in my public methods, even when it's unnecessary, because that's where the interfacing happens and it's nice to assert what's mine and what's not.

作为参考,您可以查看 Oracle 的 Java 教程关于 this.subject ;-)

As reference, you can check the Oracle's Java Tutorials out about this.subject ;-)

http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

这篇关于Java - 何时使用“this"关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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