How does the “final” keyword in Java work? (I can still modify an object.)

前端 未结 18 2300
醉酒成梦
醉酒成梦 2020-11-22 03:08

In Java we use final keyword with variables to specify its values are not to be changed. But I see that you can change the value in the constructor / methods of

18条回答
  •  孤街浪徒
    2020-11-22 03:33

    final is a reserved keyword in Java to restrict the user and it can be applied to member variables, methods, class and local variables. Final variables are often declared with the static keyword in Java and are treated as constants. For example:

    public static final String hello = "Hello";
    

    When we use the final keyword with a variable declaration, the value stored inside that variable cannot be changed latter.

    For example:

    public class ClassDemo {
      private final int var1 = 3;
      public ClassDemo() {
        ...
      }
    }
    

    Note: A class declared as final cannot be extended or inherited (i.e, there cannot be a subclass of the super class). It is also good to note that methods declared as final cannot be overridden by subclasses.

    Benefits of using the final keyword are addressed in this thread.

提交回复
热议问题