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

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

    Following are different contexts where final is used.

    Final variables A final variable can only be assigned once. If the variable is a reference, this means that the variable cannot be re-bound to reference another object.

    class Main {
       public static void main(String args[]){
          final int i = 20;
          i = 30; //Compiler Error:cannot assign a value to final variable i twice
       }
    }
    

    final variable can be assigned value later (not compulsory to assigned a value when declared), but only once.

    Final classes A final class cannot be extended (inherited)

    final class Base { }
    class Derived extends Base { } //Compiler Error:cannot inherit from final Base
    
    public class Main {
       public static void main(String args[]) {
       }
    }
    

    Final methods A final method cannot be overridden by subclasses.

    //Error in following program as we are trying to override a final method.
    class Base {
      public final void show() {
           System.out.println("Base::show() called");
        }
    }     
    class Derived extends Base {
        public void show() {  //Compiler Error: show() in Derived cannot override
           System.out.println("Derived::show() called");
        }
    }     
    public class Main {
        public static void main(String[] args) {
            Base b = new Derived();;
            b.show();
        }
    }
    

提交回复
热议问题