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

前端 未结 18 2709
醉酒成梦
醉酒成梦 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:28

    Final keyword has a numerous way to use:

    • A final class cannot be subclassed.
    • A final method cannot be overridden by subclasses
    • A final variable can only be initialized once

    Other usage:

    • When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class

    A static class variable will exist from the start of the JVM, and should be initialized in the class. The error message won't appear if you do this.

提交回复
热议问题