Final Keyword in Java rcub


Final Keyword In Java
The final keyword in java is used to preventing  the user modifications.

The final keyword can be applied with
1.variable
2.method
3.class

The final final keyword is used for finalizing the implementations of classes, methods, and Variables.

1.final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
It is used to preventing the changing the value of variable or value modification.

Syntax:  final <datatype ><variable-name >=value;

Example
class student
{
   final int rno=10;
  void change()
  { 
    rno=11;
   }
   public static void main(String args[ ])
   {
     student s=new student();
     s.change();
   }
}
Output:
Compile Time Error

2.final method
If you make any method as final, you cannot override it.
It is used to preventing the method overriding.

Syntax: final <datatype ><method-name >() {  }

Example 
class A
{
final void display()
{
System.out.println(" method in Base class");
}
class B extends A
{
  void display()  
  {
  System.out.println("method in sub   class");
}
public static void main(String args[ ])

   B o=new B() ;
   o.display();
}
}
Output:Compile Time Error

3.final class
If you make any class as final, you cannot extend it.
It is used to preventing the inheritance.

Syntax:
final class  <class -name >{      }

Example:
final class A
{
}
class B extends A
{
    void display()  
    {
    System.out.println("method in sub      class");
     }
     public static void main(String args[])
     {  
          B o=new B();
            o.display();
         }
}

Output:
Compile Time Error

Comments

Popular posts from this blog

Control Statements:Selection statement ,Iteration statement and Jump statement in Java

Abstract classes and Abstract methods in Java with Examples rcub.

Applets - Inheritance hierarchy for applets, differences between applets and applications, life cycle of an applet, passing parameters to applets, applet security issues.