Difference between Static and final?

后端 未结 11 1254
天涯浪人
天涯浪人 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:42

    The two really aren't similar. static fields are fields that do not belong to any particular instance of a class.

    class C {
        public static int n = 42;
    }
    

    Here, the static field n isn't associated with any particular instance of C but with the entire class in general (which is why C.n can be used to access it). Can you still use an instance of C to access n? Yes - but it isn't considered particularly good practice.

    final on the other hand indicates that a particular variable cannot change after it is initialized.

    class C {
        public final int n = 42;
    }
    

    Here, n cannot be re-assigned because it is final. One other difference is that any variable can be declared final, while not every variable can be declared static.

    Also, classes can be declared final which indicates that they cannot be extended:

    final class C {}
    
    class B extends C {}  // error!
    

    Similarly, methods can be declared final to indicate that they cannot be overriden by an extending class:

    class C {
        public final void foo() {}
    }
    
    class B extends C {
        public void foo() {}  // error!
    }
    

提交回复
热议问题