Demystifying Final Keyword in Java
Final a keyword in Java. Final is non-access modifier mainly used in 3 different context:
1. Variable
2. Method
3. Class
i.) Final Variable: When a variable is marked as 'final', then we cannot change it's value.
Example:
// a final static variable PI
static final double PI = 3.141592653589793;ii.) Final Method: When a method is marked as 'final', then it cannot be overridden by inheriting class.
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!");
}
}iii.) Final Class: When a class is marked as 'final' then other class cannot extend it.
Example:
final class A {
// methods and fields
}
// The following class is illegal.
class B extends A {
// COMPILE-ERROR! Can't subclass A
}Ques: Can we use 'final' with Constructor?
Ans: No, Since a final method cannot be overridden by any subclasses. And the final modifier prevents a method from being modified in a subclass.
So, in case we try to mark constructor as 'final', the Constructor cannot be inherited if a constructor is being called from child class. Therefor java does not allow final keyword before a constructor. if we'll try to add final then we'll get compile time error.
Example:
public class Example {
public static void main(String args[]){
int num;
final public Example(){
num = 30;
}
}
}Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error, insert "enum Identifier" to complete EnumHeaderName
Syntax error, insert "EnumBody" to complete BlockStatement
Syntax error, insert ";" to complete Statement
at newJavaExamples.Example.main(Example.java:6)
0 Comments