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!
static
methods is to accessstatic
fields.But you can have
static
methods, without referencingstatic
variables. Helper methods without referringstatic
variable can be found in some java classes like java.lang.MathThe other use case, I can think of these methods combined with
synchronized
method is implementation of class level locking in multi threaded environment.If you need to access method on an instance object of the class, your method should should be non static.
Oracle documentation page provides more details.
Not all combinations of instance and class variables and methods are allowed:
In eclipse you can enable a warning which helps you detect potential static methods. (Above the highlighted line is another one I forgot to highlight)
A
static
method is one type of method which doesn't need any object to be initialized for it to be called. Have you noticedstatic
is used in themain
function in Java? Program execution begins from there without an object being created.Consider the following example:
A static method has two main purposes:
If you apply static keyword with any method, it is known as static method.
//Program of changing the common property of all objects(static field).
O/P: 111 Indian BBDIT 222 American BBDIT 333 China BBDIT
No, static methods aren't associated with an instance; they belong to the class. Static methods are your second example; instance methods are the first.