Friday, March 13, 2015

Java : The final keyword

Used To Declare A Constant
final int SPEED_OF_LIGHT = 186000; // in miles per second
When placed in front of a method parameter, the final keyword prevents the method from changing the value of the parameter.
public class Klass {

   public void fooBar(final int x) {
      x = 27; // compiler error
   }
}
When the parameter is an object you can still call methods on the object. You just can't change the reference to point to a different object.
public StringBuilder fooBar(final StringBuilder strBuilder) {
   strBuilder.append("NEW");

   strBuilder = new StringBuilder("Hello World"); // Compiler Error
   // Cannot assign a value to final variable 'strBuilder'

   return strBuilder;
}
Prevent A Method From Being Overriden
public class Parent {

   public final void fooBar() {
      System.out.println("This method can't be overridden");
   }
}
public class Child extends Parent {

   public void fooBar() { // compiler error
   }
}

Prevent A Class From Being Extended
public final class Parent {

   public Parent() {
      System.out.println("This class cannot be extended");
   }
}
public class Child extends Parent { // compiler error
}
Access Local Fields Of Enclosing Method
public class Klass {

   public Klass() {
      final String str = "Hello World";

      class InnerKlass {
         public InnerKlass() {
            System.out.println("str = " + str);
         }
      }
   }
}
References
Wikipedia's "Speed of Light" article

Cay Horstman's book Big Java pages 88, 384, 568.

Java Programming : Advanced Topics (first edition) by Joe wigglesworth and Paula McMillan, pages 75, 88, 117, 154, 159, 205, 229, 233, 257.

1 comment:

  1. Final keyword in java

    Final keyword is mainly used at three places in java; at variable level to make a variable as a constant, at method level to Restrict method overriding, at class level to Restrict inheritance.

    ReplyDelete