What are the uses of the final modifier? Explain each use of the modifier with examples.
Final Modifier
- Final Modifier is a non-access Specifier that is used to restrict a class, variable, and method. If we initialize a variable with the final keyword, then we cannot modify its value.
- The final modifier keyword makes the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method.
- It's a modifier that you can apply on variables, methods, and classes and when you apply the final modifier it can make variables immutable, prevent the method from overriding in subclasses, means no polymorphism, and when you make a class final in Java it cannot be extended anymore, taking out Inheritance from the picture.
The java final modifier can be used in the following ways
(i) variable → To Create Constants
(ii) Method → To prevent Method overriding
(iii) Class → To prevent inheritance.
2nd Part
The use of each modifier is explained below with example:-
(i) To Define Constants
We can use the final modifier with variables to declare them as constant. Once the value is assigned to a final variable, we cannot change the value at runtime. If we try to change the content of the final variable the compile-time error will occur.
Example
Class Bike {
Final int speed limit = 90; // final variable
void ride() {
speed limit=90;
}
public static void main(string[] args){
Bike obj=new Bike();
obj.ride;
}
}
Output
Compile Time error
The above program will give a Compile Time error because the speed Limit is the final variable, which means we can't change the value.
(ii) To prevent overriding
we can prevent a method from being overridden from a subclass by declaring it a method as final.
Example
Class Bike {
final void ride() // final method
{
System.out.printIn ("Riding");
Class Gixxer extends Bike {
void riders() {
system.out.printIn("I'm riding bike with speed of 80km/h");
}
public static void main (string [] args)
{
Gixxer.gixxer=new Gixxer();
}
}
Output:- Compile Time Error
The above program again gives a Compile time error since we are trying to override the ride() method in Gixxer Class.
(iii) To prevent Inheritance
We can use the final modifier with a class declaration to prevent it from further inheritance. A final class cannot be further inherited.
Example
final class Bike { } // Final Class
Class Gixxer extends Bike {
Void ride()
{
system.out.printIn ("Riding safely with 100km/h");
}
public static void main(String[] args)
{
Gixxer gixxer = new Gixxer ;
gixxer.rider();
}
}
Output:- Compile-Time error.
The above program will give a compile-time error because we're trying to extend the bike class.
Comments
Post a Comment