Is final String s = “Hello World” same as String s = “Hello World”?

前端 未结 3 1815
青春惊慌失措
青春惊慌失措 2021-01-19 12:11

If a class is defined as final and we declare an instance of the final class... Would it make any difference? or is final in such cases would be re

3条回答
  •  渐次进展
    2021-01-19 12:32

    A final variable cannot be bound to another instance, so this is not valid:

    final String s = "123";
    s = "234"; // doesn't work!
    

    A final class cannot be extended

    final class A {
    }
    
    class B extends A { // does not work!
    }
    

    And both of this is not to be confused with immutable classes (like String). Instances of immutable classes won't change their state. (There is no direct language support for immutable classes, but in practice most of the time all attributes of immutable classes are declared final.)

提交回复
热议问题