WEB DEVELOPER SITE
PHP7
 

Java - Non Access Modifiers


Java provides a number of non-access modifiers to achieve many other functionalities.

  • The static modifier for creating class methods and variables.

  • The final modifier for finalizing the implementations of classes, methods, and variables.

  • The abstract modifier for creating abstract classes and methods.

  • The synchronized and volatile modifiers, which are used for threads.

The Static Modifier

The static keyword is used to create variables that will exist independently of any instances created for the class.
Static variables are also known as class variables. Local variables cannot be declared static.

Static Methods

The static keyword is used to create methods that will exist independently of any instances created for the class.

Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method. Example The static modifier is used to create class methods and variables, There are following example is give:-
public class InstanceCounter {

   private static int numInstances = 0;

   protected static int getCount() {
      return numInstances;
   }

   private static void addInstance() {
      numInstances++;
   }

   InstanceCounter() {
      InstanceCounter.addInstance();
   }

   public static void main(String[] arguments) {
      System.out.println("Starting with " + InstanceCounter.getCount() + " instances");

      for (int i = 0; i < 500; ++i) {
         new InstanceCounter();
      }
      System.out.println("Created " + InstanceCounter.getCount() + " instances");
   }
}
Try it yourself ยป

The Final Modifier

Final Variables

A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to an different object.

However, the data within the object can be changed. So, the state of the object can be changed but not the reference.

With variables, the final modifier often is used with static to make the constant a class variable.

Example

public class Test {
   final int value = 10;

   // The following are examples of declaring constants:
   public static final int BOXWIDTH = 6;
   static final String TITLE = "Manager";

   public void changeValue() {
      value = 12;   // will give an error
   }
}