point of having an instance variable as final?

前端 未结 6 430
醉梦人生
醉梦人生 2021-02-01 23:25

what is the point of having an instance variable as final?

isn´t it better to have that variable set as a static final variable then?

cause if it can\'t be chang

6条回答
  •  时光取名叫无心
    2021-02-01 23:51

    I guess you are thinking about simple case such as:

     private final int num = 3;
    

    That can be better written as:

     private static final int NUM = 3;
    

    However, often you will have references to objects that are mutable, and therefore cannot be shared between classes:

     private final List children = new ArrayList();
    

    Or perhaps, a value passed into or derived in the constructors:

     public final class MyThing {
          private final String name;
          public MyThing(String name) {
              this.name = name;
          }
          [...]
     }
    

    Note: final fields can be assigned in constructors (or instance initialiser), not just as part of the declaration.

提交回复
热议问题