Why final instance class variable in Java?

后端 未结 11 752
南方客
南方客 2020-12-09 05:13

If instance variable is set final its value can not be changed like

public class Final {

    private final int b;

    Final(int b) {
        this.b = b; 
         


        
11条回答
  •  误落风尘
    2020-12-09 05:23

    This are the usages of the keyword final that I know:

    In the class declaration

    This means that the class: cannot be sub classed

    public final class SomeClass {
    //...
    }
    

    In a global variable

    This means that once a value is assigned to it, it cannot change.

    public class SomeClass  {
         private final int value = 5;
    }
    

    There will be a compile error if you don't assign the value, but what you can do is use composition to give a value.

    public class SomeClass  {
         private final int value;
         public SomeClass(int value) {
           this.value=value
          }
    }
    

    In an object parameter

    This means that the passed object cannot be changed

    public class SomeClass {
       public void someMethod(final String value) {
          //...
       }
    }
    

    In local variables

    This means that the value cannot change once assigned

    public class SomeClass {
       public void someMethod(final String value) {
          final double pi = 3.14;
       }
    }
    

    In methods

    This means that the method cannot be overriden

     public class SomeClass {
               public final void someMethod() {
                  //...
               }
            }
    

    In collections & maps

    This means that the collection cannot be reinitialized, but it doesn't mean that the elements are inmutable, each of the elements will not be afected by the keyword final

     public class SomeClass {
           final HashMap someMap = new HashMap();
      }
    

提交回复
热议问题