final keyword is
used in different contexts. final is a non-access modifier
applicable only to a variable, a method or a class.
Following are different contexts where final
Keyword is used.
Final
at variable level:-
Final
keyword is used to make a variable as a constant. This is similar to const in
other language. A variable declared with the final keyword cannot be modified
by the program after initialization. This is useful to universal constants
Example:-
Public class
Circle
{
Public static
final pi=3.141459;
Public static
void main(String args[])
{
System.out.println(pi);
}
}
Final at method level:-
When a
method is declared with final keyword,
it is called a final method. A final method cannot be overridden. The Object class does this—a
number of its methods are final.We must declare methods with final keyword for
which we required to follow the same implementation throughout all the derived
classes. The following fragment illustrates final keyword with a method:-
class A
{
final void m1()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void m1()
{
// COMPILE-ERROR! Can't override.
System.out.println("Illegal!");
}
}
Final at
Class Level:-
We cannot extend a final class. Consider the below
example:
Example:-
final class XYZ{
}
class ABC extends XYZ{
void demo(){
System.out.println("My Method");
}
public static void main(String args[]){
ABC obj= new ABC();
obj.demo();
}
}
0 comments:
Post a Comment