A)
->”final” is a keyword in java.
->”final” modifier can be applied to variables, methods and classes as well.
->if final modifier is applied to variables, they become constants.
->final variables should be defined (should not be declared).
int a----variable declaration
int b=50; variable definition. I.e. at a time the variable declaration and initialization is done.
->once we define a final variable , we can’t assign a value to it programmatically(i.e. means we can’t change that value)
Ex:
Class A
{
final int a; //error
final int b=30; //ok
void B()
{
b=40; //error will come , so we should not assign that final variable.
}
}
->if the method is declared final, it can be inherited but can’t be overridden.
Ex:
class A
{
final void x()
{
}
}
vlass B extends A
{
void y()
{
x(); //ok, final method can be inherited
}
void x() // error. Can’t be overridden final method.
{
}
}
Explanation:
i.e. the method declared as final then that method can be inherited i.e. if that method declared in super class the subclass can be use that method but that method can’t be overriding in the sub class.
-> final class can’t be subclass. i.e. once a class is declared as final. It can’t be inherited.
Ex:
final class A
{
}
class B extends A // it is error, can’t inherited from final class.
{
}
->generally the most specialize class is declared final to indicate that further specialization doesn’t add any value to the application and hence inheritance is prevented from that point (level).
|
->some classes declared as final
Ex: Stringclass
That class declared as “final“ because that class should not inherited.
Class mystring extends string
{
} // error. The string class declared as final.
Additional information:
->So that’s why it doesn’t inherited. To provide security some classes are declared as final.
For the more security purpose only, then that type of classes should not overridden with other class methods.
->sometimes the top most (i.e. root) class is declared as final. Because to prevent the substitution.
->the bottom most class (leaf class) in the hierarchy is declared as final.
->the most specialized class in the hierarchy declared as final.
->if a class is declared as final then that class can’t inherited.
Comments
Post a Comment