static variables and static functions (methods) in Java are similar to those in C + +. There are a few things you need to review:
1) If you want to share data for all objects of a class, you can use static variables, or you can use static functions if you want to share a function.
2) If an object modifies the value of a static variable, then all objects of that class will be affected.
3) static variables and static functions can be called before a class creates an object, which is quite different from normal variable functions.
4) constants can be declared as final static, and all objects are shared.
5) Access static variables and static functions of a class, generally using the "class name. Static variable" or "class name. Static function" In a way that does not apply to object name invocation, because this can be directly seen to be called static variables and functions.
A simple base code helps to understand the use of static variables and static functions in Java.
/*** * * @author Administrator * */class Circle2 {/** * class CIRCLE2 * * data:radius, numberofobjects * * Fu Nctions:getnumberofobjects2 */double radius; static int numberofobjects; Circle2 () {radius = 1.0; numberofobjects++;} Circle2 (double newradius) {radius = Newradius; numberofobjects++;} static int getNumberOfObjects2 () {numberofobjects++; return numberofobjects;}} public class Testingstaticvariable {/** * @param args */public static void main (string[] args) {//TODO auto-generated met Hod stubSystem.out.println ("The Numebr of Objects is" + circle2.numberofobjects + "and" + circle2.getnumberofobjects2 () ); Circle C1 = new Circle (); System.out.println ("The Numebr of Objects is" + circle2.numberofobjects + "and" + circle2.getnumberofobjects2 ()); Circle c2= New Circle (10.0); System.out.println ("The Numebr of Objects is" + circle2.numberofobjects + "and" + circle2.getnumberofobjects2 ());}}
Results:
The Numebr of Objects is 0 and 1The Numebr of Objects are 1 and 2The Numebr of Objects is 2 and 3
static variables and static functions in Java