Sunday, May 8, 2016

Static and Final


Static member variables or class variables belong to the class. Unlike instance variable values, each object does not get its own unique value. A class variable belong to the class and sense there is only one class there is only one copy. When writing a class variable you must add the key word static. Later when accessing that class variable, you must use the (class_name. variable_name.)

A static method also uses the key word (static method_name.) You can access a static method by using the (class_name.method_name.) Static methods can access static variables in the class, but they can’t access instance variables.

A static method can be used if you have a method that doesn’t deal with instance data of the class. Another typical use of static method is when you access a constants. We can make or own constant variable by using the key words final and static. When making a constant variable you must set its value in the class, and it will remain constant. This mean you cannot reassign that variable later on. Below shows examples of static variables, static methods, and constants.



class Thing {

      public String name;

      public static String description;

      public final static int LUCKY_NUMBER = 7;

     

      public static int count = 0;

     

      public int id;

     

      public Thing(){

           

            id = count;

            count++;

      }

     

      public void showName(){

            System.out.println("object id; " + id + description + ":" + name);

      }

     

      public static void showInfo(){

            System.out.println(description);

           

      }

}



public class App {

      public static void main(String[] args) {

           

            Thing.description = "I am a thing";

           

            Thing.showInfo();

           

            System.out.println("Before creating objects, count is: " + Thing.count);

           

            Thing thing1 = new Thing();

            Thing thing2 = new Thing();

           

            System.out.println("After creating objects, count is: " + Thing.count);

           

            thing1.name = "bob";

            thing2.name = "sue";

           

           

            thing1.showName();

            thing2.showName();

           

            System.out.println(Math.PI);

           

            System.out.println(Thing.LUCKY_NUMBER);

        }



}


No comments:

Post a Comment