Suppose I have a class like this:
public class Car { private double distanceDriven; public void drive(double miles){ distanceDriven += miles; } public void driveInCanada(double kilometer){ distanceDriven += convertToMiles(kilometer); } private double convertToMiles(double km){ return km*0.621371192; } }
You can see that convertToMiles
is:
Should it be declared as static? This does not change the functionality of the the function at all (see above). I think that it may affect:
Should the convertToMiles
function look like:
private double convertToMiles(double km){
or
private static double convertToMiles(double km){
Instance Variables: Instance variables are non-static variables and are declared in a class outside any method, constructor or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
Instance methods should be declared static. A constructor is a method that is automatically called when an object is created. Shadowing is the term used to describe where the field name is hidden by the name of a local or parameter variable.
A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static method.
use static variables when : The value of the variable is independent of the objects (not unique for each object). E.g. number of students. Show activity on this post. Static variable: When you need something that will be used through out the application and every instance need to know the variable.
For maximum stylistic hygiene, yes, private methods that don't use any object state, but only make sense inside the object, should be static.
That's the clearest (and strictest) way of indicating how they operate, and it will helpfully force you to be careful about your design around method-boundaries, and to think twice if you decide to go change one of them later to use object data.
FWIW, I don't suspect there's a relevant performance impact here (in theory the static is easier to call due to no implicit this
reference). Also, you could go nuts being strict about this in your codebase, but it's certainly a reasonable goal to have.
N.B. Public methods require more consideration before marking them static; those can't change down the road without impact to callers, so "defaulting to tightness" isn't always the right choice.
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