Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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){         //  modify some values of baz     } }  public class Baz{     //constructor omitted      public void method(){         Bar bar = new Bar();         bar.foo(this);     } } 

Specifically, is the line bar.foo(this) acceptable?

like image 588
maxf130 Avatar asked Jul 03 '13 07:07

maxf130


People also ask

Can I pass this as a parameter in Java?

So yeah, a class can use the this keyword to refer to itself. The this keyword is also required when a local variable within a method has the same name as a class member variable, to distinguish them both.

Can I pass object in the method in Java?

Java always passes parameter variables by value. Object variables in Java always point to the real object in the memory heap. A mutable object's value can be changed when it is passed to a method. An immutable object's value cannot be changed, even if it is passed a new value.

Can call this in method in Java?

The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Yes, you can call methods using it. But, you should call them only from instance methods (non-static).

Can we pass object in method?

We can pass the data to the methods in form of arguments and an object is an instance of a class that is created dynamically. The basic data types can be passed as arguments to the C# methods in the same way the object can also be passed as an argument to a method.


1 Answers

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.

like image 134
morgano Avatar answered Sep 20 '22 15:09

morgano