Saturday 23 March 2013

what is final keyword


A final is a keyword used for three purposes.  They are
a) final as constant: A variable can be declared as constant with the keyword final.  It must be initialized while declaring.  One we initialized the variable with final keyword it cannot be modified in the program.  This is similar to the const in C/C++.
            Example:         final int x = 10;
                                    x = 45 //error

b) final to prevent overriding: A method that is declared as final cannot be overridden in a subclass method.  It the methods that are declared as private are implicitly final.
            Example:         class A
                                    {
                                                      final void show( )
                                                      {
                                                      System.out.println(“Hello”);
                                                      }
                                    }
                                    class B extends A
                                    {
                                                      void show( )
                                                      {                                                           //error
                                                      System.out.println(“Hai”);
                                                      }
                                    }

c) final to prevent inheritance: The class that is declared as final implicitly declares all of its methods as final.  The class cannot be extended to its subclass.
            Example:         final class A
                                    {
                                                      void show( )
                                                      {
                                                      System.out.println(“Hello”);
                                                      }
                                    }
                                    class B extends A                                           //error
                                    {
                                                      void show( )
                                                      {                                                          
                                                      System.out.println(“Hai”);
                                                      }
                                    }
                                         

No comments:

Post a Comment