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

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

    Yes, but you should be careful about two things

    1. Passing this when the object has not been constructed yet (i.e. in its constructor)
    2. Passing this to a long-living object, that will keep the reference alive and will prevent the this object from being garbage collected.

提交回复
热议问题