Final Keyword
The final keyword in java is used to restrict the user.The final keyword can be used in many contexts.
Variable
If you make any variable as final, you cannot change the value of final variable (It will be constant).
Example:
class num
{
final int a=90;//final variable
void run()
{
a=400;
}
public static void main(String args[])
{
num obj=new num();
obj.run();
}
}
Output:
Compile Time Error
MethodIf you make any method as final, you cannot override it.
Example:
class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}
Output:
Compile Time Error
Class
If you make any class as final, you cannot extend it.
Example:
final class Det
{
int a=10;
}
class Num extends Det
{
void run()
{
System.out.println("A is Number");
}
public static void main(String args[])
{
Num honda= new Num();
honda.run();
}
}
Output:
Compile Time Error
1 Comments
Nice 👍
ReplyDelete