Static & Final

  • when we declare a variable or a method as static , it belongs to the class rather than to a specific instance.
  • This means that only one instance of a static member exists , even if we create multiple objects of the class.
  • It will be shared by all objects.
  • Example:-
    public class Counter{
         static int count = 0;
         Counter(){
              count++;
       }
    }
  • The count variable will be shared by all object of that class.
  • Now , we can create objects of our Counter class in main & access the static variable.
  • public class Myclass{
           public class void main(String args[]){
                    Counter c1 = new Counter();
                    Counter c2 = new Counter();
                    System.out.println(Counter.count);     
          }
    }
    Output:-
    2
  • The output is 2 because the count variable is static & get incremented by one each time a new object of Counter Class is created.
  • In the above code we created a two objects.
  • we can also access the static variable using any object of class , such as c1.count.