Final Classes

A class can be declared  final when we do not want the class to be sub-classed.  We can make  a method final if it has an implementation that should not be changed by overriding it in sub-classes. Making a class final alows you to create  immutable class.  The main reasons for final methods/classes is:

  1. Security: the system can hand out sensitive bits of read-only information without worrying that they will be altered
  2. Performance: immutable data is very useful in making things thread-safe.

Examples from the Java Library

  • java.lang.String and java.lang.System

Immutable Object Definitions

In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created

Programming Example

  • Public class MyClass
  • {
  • Public void Method() {…}
  • Public final void FinalMethod() {…}
  • }
  • public class AnotherClass extends MyClass
  • {
  • public void Method() {…} //Ok
  • public final void FinalMethod() {…} //Not Ok
  • }

Leave a Reply