final keyword in java

final

The final keyword in java is used to make a variable as a constant, Restrict method overriding, Restrict inheritance.The final keyword can be used in different context.

  • final variable 

final variable is like as constant variable. Once variable  declared with final keyword, we can not modify these variable.

Example of final variable
class sample
{
final double PI=3.14;
}
class test
{
public static void main(String[] args)
{
sample obj=new sample();
System.out.println(obj.PI);
}
}

Output:
3.14

  • final method 

If we makes a method final, that means sub class can not override that method.

Example of final method
class student
{
final void disp()
{
System.out.println(“Roll no is 1″);
}
}
class college extends student
{
void disp()
{
System.out.println(“St.Villa”);
}
}
class test
{
public static void main(String args[])
{
college obj=new college();
obj.disp();
}
}

Output:
Compile time error

  • final class

If we makes the class final, that means we can not be inherited by other class.When we want to restrict inheritance then make class as a final.

Example of final class
final class student
{
int rollno=1;
}
class college extends student
{
void display()
{
System.out.println(“Roll no is 1″);
}
}
class test
{
public static void main(String args[])
{
college obj=new college();
obj.display();
}
}

Output:
Compile time error

Leave a Reply

Your email address will not be published. Required fields are marked *