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