Java final Keyword
Top level classes can be final. final is used on top level classes to make sure it cannot be extended. Hence, top level final classes cannot be abstract
final class Mountain {
}
Inside classes, final keyword can be used on Java methods, variables and nested classes.
- final variables can be assigned values only once and hence cannot be changed after assignment
- final methods are used to prevent it by being overridden in subclasses
- final nested classes cannot be extended by another class
class Peak{
final int MaxheightKM=28;
final double calculateHeight() {
int var=0;
//calculate var
return var;
}
final class Rock{
}
}
Inside intertaces, final variables and final nested classes can also be used. However, Methods inside interfaces cannot be final. Top level interfaces cannot be final.
interface Hill{
final int MaxheightKM=28;
final class Rock{
}
}
enums cannot be final. However, methods, variables, and classes inside enum can be final
enum Shapes{
CIRCLE, TRIANGLE;
final int MaxArea=5000;
final double calculateArea() {
int var=0;
//calculate var
return var;
}
final class Color{
}
}