0% found this document useful (0 votes)
6 views8 pages

Final Modifier

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views8 pages

Final Modifier

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 8

The final modifier

• The final modifier indicates that an object is fixed and


cannot be changed.
• The final is a modifier in java, which can be applied to a
variable, a method or a class.
1. When the final keyword is used with a variable then its
value cannot be changed once assigned.
2. When the final keyword is used with a method then it
cannot be overridden.
3. When a final keyword is applied to a class then the class
cannot be extended further.
1. Example of java final variable:
class A
{
final int x = 10; // final variable
void show()
{
x = 20;
System.out.println(x);
}
public static void main(String args[])
{
A obj = new A();
obj.show();
}
}
• o/p:
• Compile time error: cannot assign a value to final variable x
2. Example of java final method:
• If you make any method as final, you cannot override it.
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 obj= new Honda();
obj.run();
}
}
o/p:
Compile time error: run() in Honda cannot override run() in Bike
3. Example of java final class:
• If you make any class as final, you cannot extend it.
final class Bike
{
}
class Honda extends Bike
{
void run(){System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda obj= new Honda();
obj.run();
}
}
• o/p:
• Compile time error: cannot inherit from final Bike

You might also like