Friday, February 15, 2013

final keyword in Java

Java's final keyword can be used with lot of entities like local variables, class members (attributes, methods), classes, objects etc. Let's go in detail on each aspect:
  1. data / local variable

    If a data is declared as final then compiler ensures that you can't re-assign another value to it. Compiler also allows you to declare a final data without initializing it. In this case value needs to be initialized before it gets used. The value of a final local variable can be determined at runtime.
    public static void main(String[] args){
            final int a = 123; 
    //declared and assigned

            final String name;
            name = "Sid";  //assigned later
           
            Random r = new Random();
            final int b = r.nextInt(10);
    //not final at compile time
           
            System.out.format("a=%d; name=%s; b=%d", a,name,b);
        }
              Output : a=123; name=Sid; b=1

    Note that, multiple invocations will print different value of b (less than 10, though). So b is run time constant.
  2. class attribute/data member

     final with data members (attributes) of the class behave almost the same way as final data.
    public class FinalTest {
        private final int a =5;
        private final int b;
      // blank final member
        private final int r = new Random().nextInt(10);
           
        public FinalTest(int b) {
            super();
            this.b = b; 
      // Compile fails in absence of this initialization
        }

        public static void main(String[] args){
            FinalTest ft = new FinalTest(5);
            System.out.format("a =%d; b =%d; r=%d", ft.a,ft.b,ft.r);       
        }
    }
    Data member, b is known as blank final. Compiler in this case forces you to initialize blank finals in the constructor. Blank finals provide more flexibility as you can have different value for each object and yet retain its immutable quality.
  3. method argument 

    Arguments can be declared as final to enforce no modification inside method body. This is a good programming practice but usually it's not used consistently by developers. But one case where it's mandatory is; when you pass data to anonymous inner class.
    Read about it in detail #3 of this post
  4. method 

    Methods declared as final can't be overridden. Another reason suggested to make a method final is that it increases efficiency by making method call inline (so eliminating overhead of method call; particularly useful when method is small). But in recent JVM versions; hotspot technique can automatically detect this situation and can perform optimization. So its discouraged to declare a method as final to try help the optimizer.
    public class MyClass {
            public void myMethod() {...}
            public final void myFinalMethod() {...}
            private final void myPrivateFinalMethod() {...}
        }
    3rd method is declared as private as well as final. Is that ok?                              
    That's perfectly alright. But point to note here is that private methods can't be overridden so adding final doesn't add any value.  If a method is private it remains private and doesn't get passed down to the sub classes.
  5. class

    Class declared as final can't be subclassed. If there is never a need to make any changes to a class for safety or security reasons class can be declared as final. Declaring a class as final; implicitely makes all methods also as final as there is no way to override them. So just like previous case you can still add a final modifier but it doesn't add any value.                                                                                                                                                                                                                                                     Final classes from Java API : java.lang.String, java.lang.Math, java.lang.Integer, java.lang.Double, java.lang.Short, java.lang.Void and other java.lang package classes                                          

1 comment:

  1. This article is very nice i like it this is paragraph is so nice its very informative.

    PIC Bonus Singapore

    ReplyDelete