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

后端 未结 10 1153
无人共我
无人共我 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:43

    Yes. you can use it.Its just common in programming to pass this.But there are pros and cons about using that.Still it is not hazardous to do so.

    0 讨论(0)
  • 2021-01-30 19:47

    this stands for the current object. What you are doing is sytatically correct but i don't see a need of this if you are calling the method in the same class.

    0 讨论(0)
  • 2021-01-30 19:49

    Everything in java is passed by value. But objects are NEVER passed to the method!
    When java passes an object to a method, it first makes a copy of a reference to the object, not a copy of the object itself. Hence this is pefectly used method in java. And most commonly followed usage.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-30 19:56

    Acceptable

    Snippet from Oracle JAVA docs:

    Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

    Using this with a Field

    The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

    0 讨论(0)
  • 2021-01-30 19:58

    There's nothing wrong with that. What is NOT a good practice is to do the same inside constructors, because you would give a reference to a not-yet-completely-initialized object.

    There is a sort of similar post here: Java leaking this in constructor where they give an explanation of why the latter is a bad practice.

    0 讨论(0)
提交回复
热议问题