The final keyword in java is used to restrict the user. The final keyword can be used in many context. Final can be:
Final variable :
If you make any variable as final, you cannot change the value of final variable(It will be constant).
//can't assign a value to final variable class Simple{ final int a=50; void change(){ a=100; //CTE } public static void main(String args[]){ Simple S=new Simple(); S.change(); System.out.println(S.a); } }
Final method :
final keyword in java :: futureX |
- variable
- method
- class
Final variable :
If you make any variable as final, you cannot change the value of final variable(It will be constant).
//can't assign a value to final variable class Simple{ final int a=50; void change(){ a=100; //CTE } public static void main(String args[]){ Simple S=new Simple(); S.change(); System.out.println(S.a); } }
Final method :
If you make any method as final, you cannot override it.
//overriden method is final CTE
class A{
final void m(){System.out.println("hello");}
}
class Simple extends A{
void m(){System.out.println("java");}
public static void main(String args[]){
Simple S=new Simple();
S.m();
}
}
Final class :
If you make any class as final, you cannot inherit it.
//cant inherit from final class CTE
final class A{}
class Simple extends A{
public static void main(String args[])
{}
}
No comments:
Post a Comment