Monday, 8 June 2015

Java Other modifiers for top-level classes

Besides visibility modifiers, we can also use following modifiers before a top-class:

(a) abstract, and (b) final

(a) abstract

A class can be specified with the keyword abstract to indicate that it cannot be instantiated. A class containing abstract method must be declared as abstract otherwise it won’t compile. A class not containing any abstract method can also be declared abstract. Such a class can serve as a base class for a number of sub-classes.

(b) final

A class can be declared final to indicate that it cannot be extended. The final class marks the lower boundary of its implementation inheritance hierarchy. Only a class whose definition is complete can be declared final. A class cannot be both final and abstract at the same time.

Here are few important characteristics of the final class.

  • All the methods of a final class are also final i.e. they have the concrete implementation and cannot be over-ridden.
  • Some type checks become faster with final classes. In fact, many type checks become compile time checks and errors can be caught earlier. If the compiler encounters a reference to a final class, it knows that the object referred to is exactly of that type.

  • The compiler is able to perform certain code optimizations for final methods, because certain assumptions can be made about such members. When a non-final method is invoked, the run time system determines the actual class of the object, binds the method invocation to the correct implementation of the method for that type, and then invokes the implementation. In case of a final method we are sure that sub-class cannot override the method so the binding is done at the compile time as in case of private and static methods, which would definitely improve the performance.

  • In case of a final method the compiler may replace an invocation with the actual body of the method like Macro. This mechanism is known as ‘inlining’. In C++, we have the option of declaring a function as inline (although final decision is taken by the compiler) but in Java, the compiler takes the decision.

No comments:

Post a Comment