Is passing 'this' in a method call accepted practice in java

后端 未结 10 1211
无人共我
无人共我 2021-01-30 19:32

Is it good/bad/acceptable practice to pass the current object in a method call. As in:

public class Bar{
    public Bar(){}

    public void foo(Baz baz){
              


        
10条回答
  •  庸人自扰
    2021-01-30 19:54

    There's no reason not to use it, this is the current instance and it's perfectly legitimate to use. In fact there's often no clean way to omit it.

    So use it.

    As it's hard to convince it's acceptable without example (a negative answer to such a question is always easier to argument), I just opened one of the most common java.lang classes, the String one, and of course I found instances of this use, for example

    1084        // Argument is a String
    1085        if (cs.equals(this))
    1086            return true;
    

    Look for (this in big "accepted" projects, you won't fail to find it.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题