Search This Blog

What is 'final' in Java?

final is a keyword in java which is used to protect java class/method/variables from unwanted modification. Uses of final in different context is as below:
  1. final variable :  If a variable is declared as final, value of that variable can't be changed.it can be initialized but once, either by assigning the value or via an initializer. A blank final instance variable must be assigned in each constructor of the class. Otherwise a compile time error occurs. Unlike constant (static final) final variables is not necessarily known at compile time. It is considered good practice to declare final variable in uppercase and words separated bu underscore.
  2. public class FinalExample {
     final int x=10;
    }
    
  3. final method :  If a method is declared as final, that method can't be overridden in its subclass. This is used to prevent unexpected behavior from subclass in case it override the method from super class.
  4. public class FinalExample {
    
     final int x=10;
     final String finalMethod(){
      return "final Method";
     }
    }
    
  5. final class :  If a class us declared as final,  that class can not be subclassed. Making class final ensures the security and efficiency i. e. One of the reason why some of  the java API classes are declared as final eg. java.lang.String etc.
  6. public final class FinalExample {
     //Code goes here. Methods inside this class are by default final
    }
    

No comments:

Post a Comment