Sunday, January 12, 2014

Final keyword examples in Java

In this post, we see the different use of final keyword when it's applied to class, methods and variables.


Final Classes


Final methods


Final variables


Final Objects


Final Arguments



Final classes
A final class is a non-inheritable class—that is to say, if you declare a class as final, you cannot subclass it.In other words, no other class can ever extend (inherit from) a final class, and any attempts to do so will give you a compiler error.

So why would you ever mark a class final? After all, doesn't that violate the whole object-oriented (OO) notion of inheritance?

In some cases you don’t want to allow a class to be sub classed. Two important reasons are
  • To prevent a behavior change by sub-classing. In some cases, you may think that the implementation of the class is complete and should not change. If overriding is allowed, then the behavior of methods might be changed. You know that a derived object can be used where a base class object is required, and you may not prefer it in some cases. By making a class final, the users of the class are assured the unchanged behavior
  • Improved performance. All method calls of a final class can be resolved at compile time itself. As there is no possibility of overriding the methods, it is not necessary to resolve the actual call at runtime for final classes, which translates to improved performance. For the same reason, final classes encourage the inlining of methods. If the calls are to be resolved at runtime, they cannot be inlined.

You'll notice many classes in the Java core libraries are final. For example, the String class cannot be subclassed. Imagine the havoc if you couldn't guarantee how a String object would work on any given system your application is running on! 
So use final for safety, but only when you're certain that your final class has indeed said all that ever needs to be said in its methods. Marking a class final means, in essence, your class can't ever be improved upon, or even specialized, by another programmer.

Another example, java.lang.System. These classes are used extensively in almost all Java programs. For example, if you use a System.out.println() statement, you are using both the System class as well as the String class since println takes String as an argument.If these two classes are not declared final, it is possible for someone to change the behavior of these classes by subclassing and then the whole program can start behaving differently

A benefit of having nonfinal classes is this scenario
Imagine you find a problem  with a method in a class you're using, but you don't have the source code. So you can't modify the source to improve the method, but you can extend the class and override the method in your new subclass, and substitute the subclass everywhere the original superclass is expected. If the class is final, though, then you're stuck.


Final Methods
In a class, you may declare a method final. The final method cannot be overridden. Therefore, if you have declared a method as final in a non-final class, then you can extend the class but you cannot override the final method. But, other non-final methods in the base class can be overridden in the derived class implementation.
It often used to enforce the API functionality of a method.
For example, the Thread class has a method called isAlive() that checks whether a thread is still active. If you extend the Thread class, though, there is really no way that you can correctly implement this method yourself (it uses native code, for one thing), so the designers have made it final.
Just as you can't subclass the String class you can't override many of the methods in the core class libraries.
class test{  
      final void print(){  
           System.out.println("hello test");  
      }  
 }  
 public class FinalMethodOverride extends test{  
      void print(){ // error  
           System.out.println("Hello overloaded test");  
      }  
 }  

Final variables
Using the "final" keyword makes the the variable you are declaring immutable. Once initially assigned it cannot be re-assigned.

Final variables are like CD-ROMs: once you write something on them, you cannot write again. In programming, universal constants such as PI can be declared as final since you don’t want anyone to modify the value of such constants. Final variables can be assigned only once. If you try to change a final variable after initialization, you will get a complaint from your Java compiler.
public class FinalVariable{  
      public static void main(String javalatt[]){  
           final int i = 10;  
           i = 10; // error  
      }  
 } 


Reasons why you would use the "final" keyword on variables
  • Optimization where by declaring a variable as final allows the value to be memoized
  • You would use a final variable is when an inner class within a method needs to access a variable in the declaring method.
Example
public class FinalVarialbeOne {  
      public static void main(String java[]){  
           new Hello().go();  
      }  
      public void go(){  
           final int counter = 5;  
           new Runnable() {  
                @Override  
                public void run() {  
                     int i = counter;  
                     System.out.println("i="+i);  
                }  
           }.run();  
      }  
 }  
Sample Output

i=5



Final Object
The value of a final parameter cannot be changed once assigned. Here, it is important to note that the “value” is implicitly understood for primitive types. However, the “value” for an object refers to the object reference, not its state.
class Test2{  
      private int i = 10;  
      void setValue(int i){  
           this.i=i;  
      }  
      int getValue(){  
           return this.i;  
      }  
 }  
 public class FinalMethodOverride extends test{  
      public static void main(String javalatte[]){  
           final Test2 ts1 = new Test2();  
           ts1.setValue(100);  
           ts1 = new Test2(); //error   
      }  
 }  
If an object is final you can call any methods that do internal changes as usual, but you cannot reassign the reference to point to a different object


Final Arguments
Method arguments are the variable declarations that appear in between the parentheses in a method declaration.

public void sum(int a, final int b)

In this example, the variable b is declared as final, which of course means it can't be modified within the method. In this case, "modified" means reassigning a new value to the variable. In other words, a final argument must keep the same value that the parameter had when it was passed into the method.


Points to Remember

  • Final stop value change.
  • Final stop method overriding.
  • Final stop inheritance.
  • The final modifier can be applied to a class, method, or variable. All methods of a final class are implicitly final (hence non-overridable).
  • A final variable can be assigned only once. If a variable declaration defines a variable as final but did not initialize it, then it is referred to as blank final. You need to initialize a blank final all the constructors you have defined in the class; otherwise the compiler will complain.
  • The keyword final can even be applied to parameters. The value of a final parameter cannot be changed once assigned. Here, it is important to note that the “value” is implicitly understood for primitive types. However, the “value” for an object refers to the object reference, not its state. Therefore, you can change the internal state of the passed final object, but you cannot change the reference itself.



If you know anyone who has started learning java, why not help them out! Just share this post with them. 
Thanks for studying today!...

4 comments:

  1. Very Nice Quick Reference Article about all variations of Final keyword.
    Thanks for sharing it.

    ReplyDelete
  2. I'd like to make one more point: Documentation. Final not just improves performance and security to me it's also part of the Api documentation.
    Thx for your post

    ReplyDelete
  3. 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