Wednesday 21 March 2018

Final Keyword in Java(Class,Method,Variable)


Final Keyword, Java, keyword, final in java,Final Keyword in Java(Class,Method,Variable) final keyword. The final is a keyword.Final can be variable, method, class or parameter. Let's see. Final Keyword in Java(Class,Method,Variable), Java Class,Method,Variable,  Final Keyword , Java Final, Final in java, Java final keyword, java final keyword, Explain final, final keyword, final, what is final keyword

Final Keyword 

The final keyword is used to restrict the user.

The java final keyword can be used in many contexts...

1. Class

2. Method

3. Variable 

#1 Java final variable

When final keyword applied to a variable, the variable becomes a constant. So, you can not change its value in the program. It can be used as just read-only. 

Example :

class Hero

{
   final int speedlimit=90
   void run()

   {
        speedlimit=400;
   }
   public static void main(String args[])

   {
       Hero obj=new  Hero();
       obj.run();
   }
}

#2 final Method:

When final keyword applied to a method it can not be overridden by it's subclass that is you can use final to prevent overriding a method.

Example of the final method :


class Car
{
    final void run()
    {
            System.out.println("running");
    }
}
class Honda extends Car
{
   void run()
   {
             System.out.println("running safely with 100kmph"); 
    }
  
   public static void main(String args[])
   {
         Honda honda= new Honda();
         honda.run();
   }
}

#3 Final Class

Final class can not be extends by any class. That is a final class can not use final keyword to prevent inheritance.

Several classes in java are final class.

We can declare the final class using 'final' keyword.

Example:  

final class Hero
{

}   
class Honda extends Hero

{
   void run()

   {
          System.out.println("Hero Honda");
   } 
  public static void main(String args[])

  {
          Honda honda= new Honda();
          honda.run();
  }

 

 


 


Popular posts