Difference between Static and final?

后端 未结 11 1317
天涯浪人
天涯浪人 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 and final have some big differences:

    Static variables or classes will always be available from (pretty much) anywhere. Final is just a keyword that means a variable cannot be changed. So if had:

    public class Test{    
       public final int first = 10;
       public static int second = 20;
    
       public Test(){
         second = second + 1
         first = first + 1;
       }
    }
    

    The program would run until it tried to change the "first" integer, which would cause an error. Outside of this class, you would only have access to the "first" variable if you had instantiated the class. This is in contrast to "second", which is available all the time.

提交回复
热议问题