How to Do Static Floats in Java

In the Java programming language, every variable needs to be explicitly declared as a member of a class. Java includes pre-defined classes for some common datatypes such as "Integer" and "Float" (a simple-precision floating-point number). If you apply the "static" modifier to a variable declaration, Java interprets that there is a single instance of that variable for the whole class, instead of the default interpretation (a separate instance for each existing object of that class). You can declare a float variable while using the "static" modifier.

Instructions

    • 1

      Declare a new class to house the static float variable, as in the following example:

      public class Notch{

      }

    • 2

      Add declarations for all state variables that need to be replicated in every instance of the new class, as follows:

      public class Notch{

      private float displacement;

      private String name;

      }

      By default, class variables are not static.

    • 3

      Add the declaration for the static variable (one instance per class) as follows:

      public class Notch{

      private float displacement;

      private String name;

      private static float sumAllDisplacements = (float)0;

      }

      In this example, the static float variable will keep (when complemented by the appropriate class methods) the sum of the displacements of all Notch instances created so far.

Related Searches:

References

Comments

Related Ads

Featured