1) final variable : When the variable in a class is declared as final, then its value remains the same. Its considered as a constant. It cannot be changed. When a variable is declared final, then it needs to be initialized only once, using an assignment operator or in initializer. If the final variable is not assigned a value at the time of declaration, then it is considered as "blank final" variable. In this case, it need to be mandatorily initialzed in a constructor or in a static block in the class.
Java compiler will ensure that the blank final is not used until it is assigned a value and that once assigned a value, the now final variable cannot be reassigned another value.
Java compiler will ensure that the blank final is not used until it is assigned a value and that once assigned a value, the now final variable cannot be reassigned another value.
public class FinalVariables
{
public static final double declaredFinal 3.85;
public final double radius;
FinalVariables(double r) {
radius = r;
}
}
2) final method : When a method is made final, then this method cannot be overloaded in case some other class is extending the class containing the final method.public class Base
{
public final void m2() {...}
}
public class Derived extends Base
{
public void m2() {...} // not allowed, gives compilation error
}
3) final class : When a class is made final, then it cannot be subclassed.
public final class FinalClass {...}
public class ThisIsWrong extends FinalClass {...} // not allowed, gives compilation error
No comments:
Post a Comment