Sunday, January 24, 2016

Topic 25: Inheritance and Keyword final

The keyword final was used to create the equivalent of a named constant in earlier articles. The other two uses of final apply to inheritance.

  • To disallow a method overriding, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. The following fragment illustrates final:

class A
{
final void meth()
{
System.out.println("This is a final method.");
}

}
class B extends A
{
void meth() // ERROR! Can't override.
{
System.out.println("Illegal!");
}

}

Because meth( ) is declared as final, it cannot be overridden in B. If we attempt to do so, a compile-time error will result.

  • To prevent a class from being inherited, precede the class declaration with final. 

    Declaring a class as final implicitly declares all of its methods as final, too. 

    It is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.

Here is an example of a final class:
final class A
{
// ...
}

Cannot inherit the class declared as final. The following class is illegal.

class B extends A // ERROR! Can't subclass A
{
// ...
}

 

Click for NEXT article.

 

Please feel free to correct me by commenting your suggestions and feedback.

No comments:

Post a Comment