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?
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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With