Contents
When to pass a member variable as a method parameter?
However if the method always works on a single member it seems a bit dumb to pass it as a parameter. The main reason for having a member variable in a class is to allow you to set it in one place, and have it’s value available to every other method in the class.
How are primitive arguments passed into a method?
Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost.
When do you pass arguments to a method in Java?
Note: Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration’s parameters in type and order.
Do you have to use someMethod as a method parameter?
And since SomeMethod in your example is protected, subclasses will also need to change. Methods (public or private) that do not depend on the class internals do not need to be on that class. They could be factored out into utility methods and be just as happy. They have next to no business being part of that class.
How to use a member variable as the default?
To get around this, you need 2 overloads of your MoveTo method. One that takes 1 argument, and another that takes 2 arguments. The method taking 1 argument calls the other method, passing along the value that you consider as the default.
When to use member field as a parameter?
I can think of a justification for passing a member field as a parameter in a (private) method: it makes explicit what your method depends on. Like you say, all member fields are implicit parameters of your method, because the whole object is. However, is the full object really needed to compute the result?
Why do you have a member variable in a class?
The main reason for having a member variable in a class is to allow you to set it in one place, and have it’s value available to every other method in the class. In general therefore you would expect that there is no need to pass the member variable into a method of the class.