Java final keyword tutorial


The final keyword is used to restrict some related member variable, method or class.

  • final variables

    Once you initialize the final variable, you cannot modify it. There are 3 possible types of final variable initializations.


    • final variable can initiazile in a assignment statement

    • final variable can initiazile in a constructor

    • static final variable can initiazile in a static block

    public class StaticClass {
        private final String VAR_1 = "VAR_1";         //initiazile in a assignment statement
        private final static String VAR_2 = "VAR_2";  //initiazile in a assignment statement
    
        private final String VAR_3;
    
        private final static String VAR_4;
    
        static {
            VAR_4 = "VAR_4";                    //initiazile in a static block
        }
    
        public StaticClass() {
            VAR_3 = "VAR_3";                    //initiazile in a constructor
        }
    }


  • final class

    A final class cannot be subclassed. You cannot extend a final class into another.



  • final methods

    A final method cannot be overridden in a subclass. That class will be a concrete class for parent class and children both.

        public class Bird {
            private String name;
            public Bird(String name) {
                this.name = name;
            }
            protected final void sing() {
                System.out.println("Bird " + name + " is singing");
            }
        }

    We will get a similar error like below during the compilation if we try to override the final method in a child class.

    HummingBird.java:17: error: sing() in HummingBird cannot override sing() in Bird
            protected void sing() {
                           ^
          overridden method is final
        1 error
        

<< Java static keyword      Java new keyword >>