I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
e.g
Obj x = new Obj();
x.someMethod
or
Obj.someMethod
(is this the static way?)
I'm rather confused!
Use a static method when you want to be able to access the method without an instance of the class.
Static methods and variables are controlled version of 'Global' functions and variables in Java. In which methods can be accessed as
classname.methodName()
orclassInstanceName.methodName()
, i.e. static methods and variables can be accessed using class name as well as instances of the class.Class can't be declared as static(because it makes no sense. if a class is declared public, it can be accessed from anywhere), inner classes can be declared static.
Actually, we use static properties and methods in a class, when we want to use some part of our program should exists there until our program is running. And we know that, to manipulate static properties, we need static methods as they are not a part of instance variable. And without static methods, to manipulate static properties is time consuming.
One rule-of-thumb: ask yourself "does it make sense to call this method, even if no Obj has been constructed yet?" If so, it should definitely be static.
So in a class
Car
you might have a methoddouble convertMpgToKpl(double mpg)
which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. Butvoid setMileage(double mpg)
(which sets the efficiency of one particular Car) can't be static since it's inconceivable to call the method before any Car has been constructed.(Btw, the converse isn't always true: you might sometimes have a method which involves two
Car
objects, and still want it to be static. E.g.Car theMoreEfficientOf( Car c1, Car c2 )
. Although this could be converted to a non-static version, some would argue that since there isn't a "privileged" choice of which Car is more important, you shouldn't force a caller to choose one Car as the object you'll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.)Define static methods in the following scenarios only:
Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.