Friday, July 20, 2012

final method


Why do we need to mark a class as final ?

Sometimes we need to write some important classes where the implementation logic should remain unchanged for all the methods. In these type of scenarios we use final class.In java final classes can't be subclassed means final class cannot be inherited so the implementation logic can't be changed/modified/removed in subclasses. String class is a final class

A method declared final can't be overridden in subclasses.

A member variable declared as final cannot change its value.Changing the value will result in a compile time error. In java final variable is not initialized by default. They have to be assigned a value at the time of declaration or in an initialize block or in the constructor of the class.


Method arguments marked as final cannot be reassigned any value they are behaved as read only.

Example code below 

package com.fastlearned;

public final class FinalVariableTest {

 private final int CONST_INT = 12;
 private final String CONST_STRING;

 /*
  * constructor
  */
 FinalVariableTest() {
  // final variable initialized in
  // a constructor
  CONST_STRING = "Constant String";
 }

 /*
  * This is a final method
  */
 public final void testfinalMethod() {
  System.out.println("final method can't be overridden");
  System.out.println(CONST_INT + " -- " + CONST_STRING);
 }

 /*
  * This is a protected method where the arguments are final
  */
 protected void testProtectedMethod(final int a, final int b) {
  System.out.println("Sum of two final variable is " + (a + b));
 }

 public static void main(String[] args) {

  FinalVariableTest variableTest = new FinalVariableTest();
  variableTest.testfinalMethod();
  variableTest.testProtectedMethod(10, 20);
 }

}



No comments:

Post a Comment