February 1, 2011

Effect of final keyword on variables, methods & classes in Java

Effect on final on variables
A primitive variable marked final cannot be reassigned once it has been initialized with an explicit value
A reference variable marked final cannot be reassigned to refer to a different object, though the state of the object can be changed.

public class Test {
  
   String s;  

   public static void main(String args[]) {
      final int i;
      i = 3;
      i = 4;              // will not compile

      final Test t;
      t = new Test();
      t.s = "Hello";
      t.s = "World";

      t = new Test();     // will not compile

   }
}

Effect on final on methods
Methods marked as final cannot be overridden in the subclass.

public class Test {
   public final void m1() {
      System.out.println("Superclass");
   }
}

public class A extends Test {
   public void m1() {                 // will not compile
      System.out.println("Subclass");
   }
}

Effect on final on classes
Classes marked as final cannot be subclassed.

public final class Test {

}

public class A extends Test {       // will not compile

}

No comments:

Post a Comment