In: Computer Science
What does it mean when a class, method and varaible is declared final?
Final class- If a class is declared as final, then it becomes final class. A final class cannot extend to another class. Therefore, we cannot access variables, methods present inside a final class to other class. Final class can be used to prevent inheritance of a class.
Final method- If a method is declared as final, it means the method cannot be overriden. Any attempt to override a final method of the superclass will result in compiler error. Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. The implementation in the subclass overrides (replaces) the implementation in the superclass by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class. Private methods of the superclass are automatically considered to be final. This is because we cannot override a method in the subclass . Similarly, the static methods are also implicitly final as they also cannot be overriden.
Final variable- When a variable is declared as final, it means its value cannot be modified. It means it is a constant.
Therefore, if a class, method and a
variable is declared final it means that the class cannot be
inherited, method cannot be overriden and the value of a variable
cannot be changed, that is it is a constant.