How and where to use Static modifier in Java?
You can think of a 'static' method or field as if it were declared outside the class definition. In other words
- There is only one 'copy' of a static field/method.
- Static fields/methods cannot access non-static fields/methods.
There are several instances where you would want to make something static.
The canonical example for a field is to make a static integer field which keeps a count across all instances (objects) of a class. Additionally, singleton objects, for example, also typically employ the static modifier.
Similarly, static methods can be used to perform 'utility' jobs for which all the required dependencies are passed in as parameters to the method - you cannot reference the 'this' keyword inside of a static method.
In C#, you can also have static classes which, as you might guess, contain only static members:
public static class MyContainer
{
private static int _myStatic;
public static void PrintMe(string someString)
{
Console.Out.WriteLine(someString);
_myStatic++;
}
public static int PrintedInstances()
{
return _myStatic;
}
}
When to use static methods
One rule-of-thumb: ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static.
So in a class Car
you might have a method:
double 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
. But this method (which sets the efficiency of one particular Car
):
void setMileage(double mpg)
...can't be static since it's inconceivable to call the method before any Car
has been constructed.
(By the way, 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.
Java constants and static modifiers
If you assign a value to the final
variable when declaring it, there's no point in it not being static
, since each instance would have its own variable having the same value, which is wasteful.
However, if you need an instance variable whose value can only be set once (but different instances may have different values), that variable would have to be final
but not static
.
For example :
class Person
{
final int id;
public Person(int id) {
this.id = id;
}
}
Static modifier from C++, but in Java?
looks like you are starting with java. To help you understand the concept i wrote the same code with comments for your understanding.
package yourXYZpackage;
public class yourABCclass{
//Declare in class body so your methods(functions) can access //and the changes made will be global in C++ context. static int count=0;
void counter() { count = count++; System.out.println(count); //thats how you can display on console } //this is the main method like C++ public static void main(String[] args){ for(int i=0;i<5;i++) { counter(); } }}
Related Topics
Calling Win32 API Method from Java
How to Convert Pojo to JSON and Vice Versa
Java Convert Gmt/Utc to Local Time Doesn't Work as Expected
Java - Why No Return Type Based Method Overloading
Java Int to String - Integer.Tostring(I) VS New Integer(I).Tostring()
Which Concurrent Queue Implementation Should I Use in Java
Use of Java [Interfaces/Abstract Classes]
Why Do We Have to Override the Equals() Method in Java
What Does This Thread Join Code Mean
How Does the Bitwise & (And) Work in Java
Java's Bigdecimal.Power(Bigdecimal Exponent): Is There a Java Library That Does It
Java Change the Document in Documentlistener
What Does Maven Do, in Theory and in Practice? When Is It Worth to Use It
Difference Between List and Array
Stopping a Window from Displaying Till It Is Fully Drawn
Printing in Java to Label Printer
Java.Sql.Sqlexception: Incorrect String Value: '\Xf0\X9F\X91\Xbd\Xf0\X9F...'