Using final with inheritance Java Help

Using final with inheritance

The keyword final has three Uses. First, it can be used to create the equivalent of a  .named constant. This use was described in the preceding chapter. The other two uses  of final apply to inheritance. Both are examined here

Using final to Prevent Overriding

While method overriding is one of most powerful features, there will be times when you will want to prevent it from occurring. To disallow a method from being  overridden. specify final as a modifier at the start of its declaration. Methods declared’ as final cannot be overridden. The following fragment illustrates final.

Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to
do so, ‘a compile-time error will result. Methods declared as final can sometimes provide a performance enhancement: The ‘ Compiler is free to inline calls to them because it “mows” they will not be overridden by , a subclass. When a small lam function is called, often the Java compiler can copy the byte code for the subroutine directly inline with the compiled code of the calling method, thus eliminating the costly overhead associated with a method’call. In lining is only an option with final methods. Normally, Java resolves.calls to methods dynamically t run time. This is called late binding. However, since final methods   one can be resolved at compile time.

Using final to Prevent Inheritance

Sometimes you will want to prevent a class from inherited. To do this, precede the class declaration with final. Declaring a class as final implicitly d!dares all of its: methods as final, too. As you might expect, ,it is illegal to declare a as both abstract and final since an abstract class is incomplete by itself and upon its  to provide complete  implementations. He re is an example of a final class.

  • Feel free to send us an inquiry, we will reply back in hours.


Posted on September 17, 2014 in Inheritance

Share the Story

About the Author

Back to Top