What are Static Fields and Methods? - Java Tutorials
Every program that you make in Java main method is always tagged with the keyword static. Similar to main other method (as well as Fields) can be defined as static.
Static Fields
If a field is defined as static it will mean that there will be only one instance of such field. Consider the following code:
class Employee{ private int empId; private static int nextId = 1; private String empName; Employee(String name){ empName = name; empId = nextId; nextId++; } void getDetails(){ System.out.println("ID: " + empId); System.out.println("Name: " + empName); } }
The above class assigns a unique id to every employee that is created. Here, nextId is defined as static which means that there will be a single unique nextId available for all objects. For example, if we make 100 objects of Employee class there will be 100 empId and empName, but only 1 nextId created. The static field (nextId in this case) will be common for all objects.
Static Constants
Static variables are quite rarely used or defined. However, static constants commonly used, consider the following example:
class someMathsClass{ ... private static final double pi = 3.14159265358979323846; ... }
Here we use the keyword final to make pi a constant and the keyword static makes sure that there is only one copy of it available for all objects.
Static Methods
Static methods are the ones that do not operate on objects. To call a static method we use the class name followed by '.', for example:
The pow defined in Math class is static. So, you do not need to make an object of Math to use pow, to call pow you simply write:
Math.pow(a, b)
Since, static methods do not operate on objects they cannot make a call to instance variable but you can make a call to static variable from static methods.
0 comments: