Pages

Sunday, May 10, 2020

Final Keyword in Java


Summary of Final:
Summary of Final Variable



Final

First of all final, public, private, protected, static, abstract are modifiers in java (Please see below screenshot of an eclipse).


1.    Final is a modifier which can apply to the class, method and variables.

2.    Final class can NOT extend by any normal class.

3.    Final method can overload but can NOT override.

4.    Final variable value can NOT change once assigned. If we haven’t assign any value then Sun Micro System allow to assign value only inside constructor.

5.    It is used to declare constant values e.g. pi=3.141, g=9.8.

6.    Final & abstract combination not allowed in java.

7.    Interfaces, block, constructors Can’t final.

8.    It is used to restrict inheritance.

9.    Used to create an immutable class.

10.  Wait(), notify(), notifyAll() etc. are e.g. of final methods of Object class.

11.  Example of final classes are: String class, all wrapper classes, System class

12.  Static final combination is allowed in java e.g. variables in interfaces are static final  by default.


Examples:


    public class A {
          final int i//The blank final field i may not have been initialized
                    }

               // After assigning value in constructor it will not give an error:
public class A {
 final int i//blank final
A()
{
         i=15;
}
           }
   

Restriction using Final:



Also below are NOT allowed for final:

final class A {
         
          final abstract m1(); //final abstract combination not allowed
          
          final {
                 
                    } //final can't apply to block     

          final A() {  //can't apply to constructor

                       }       
             }


    static final variable:

      class A {
           static final int i; //we can't initialize this i in constructor
           static {
                    i=50;
                  } //if static final variable then we initialize it in static block only
           
           A() {
                    i=40; //error as:- The final field A.i cannot be assigned
               }      
          }
  

Calling final method: 

      class A {
           public final void m1()
           {
           System.out.println("in final m1()");
           }
      }
           class B extends A{
           public static void main(String[] args) {
                   A a=new A(); 
                   a.m1();

                   B a1=new B();
                   a1.m1();

                   A a2=new B();
                   a2.m1();
                   }
            }

Output:
In final m1()
In final m1()
In final m1()








No comments:

Post a Comment

**** Please let me know if you have any doubts. ****