What Is Static in Java?

104 14

    Classes

    • Inside a Java class declaration, programmers define the behavior that objects of the class will implement. Instance variables appear within most class declarations. If a class contains one or more instance variables, each object instance of the class will have its own copy of these. The following sample code is a typical example of an instance variable appearing within a class declaration:

      String myName;

      The constructor method for the class could instantiate this variable as follows:

      public Person(String name) {

      myName = name;

      }

      In this case the class, named "Person," has a constructor function which takes a string parameter representing the name for an individual instance of the class. To create an object of the class, programs could use the following code:

      Person aPerson = new Person("Mary");

    Variables

    • Unlike instance variables, static variables belong to a class, rather than to specific instances of it. This means that there is only one copy of a static variable, which is accessible from all members of the class, as well as from external "customer" code via objects of the class. For example, a static variable could keep track of a property within the application which remains the same for all class members. The following sample code demonstrates declaring a static variable inside a class declaration:

      private static int numWomen = 0;

      Within the class constructor or another method, the variable can be accessed and updated as follows:

      numWomen++;

    Methods

    • Class declarations can include static methods. As with variables, static methods provide some functionality that is the same across all object instances of a class. Static methods commonly carry out processing that involves static variables. The following sample static method returns the value of a static variable within a class declaration:

      public static int getNumWomen() {

      return numWomen;

      }

    Access

    • Java code does not need to create an instance of a class to call static methods. For example, the following syntax demonstrates calling the method on the class itself:

      Person.getNumWomen();

      Many programmers first experience this technique when using classes of the Java language, rather than their own classes, as in the following example:

      System.out.println("Hello");

      This code uses the System class to write a text string to the output console. Programs can access both static variables and methods using the class name rather than the name of an object instance of the class.

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.