Difference between Static and final?

后端 未结 11 1258
天涯浪人
天涯浪人 2020-11-27 08:51

I\'m always confused between static and final keywords in java.

How are they different ?

11条回答
  •  清酒与你
    2020-11-27 09:29

    Static is something that any object in a class can call, that inherently belongs to an object type.

    A variable can be final for an entire class, and that simply means it cannot be changed anymore. It can only be set once, and trying to set it again will result in an error being thrown. It is useful for a number of reasons, perhaps you want to declare a constant, that can't be changed.

    Some example code:

    class someClass
    {
       public static int count=0;
       public final String mName;
    
       someClass(String name)
       {
         mname=name;
         count=count+1;
       }
    
      public static void main(String args[])
      {
        someClass obj1=new someClass("obj1");
        System.out.println("count="+count+" name="+obj1.mName);
        someClass obj2=new someClass("obj2");
        System.out.println("count="+count+" name="+obj2.mName);
      }
    }
    

    Wikipedia contains the complete list of java keywords.

提交回复
热议问题