final variables

A final variable cannot be modified.

You must initialize a final variable when it is declared. A final variable is essentially a constant.

 
public class Main {
  final int FILE_NEW = 1;
  final int FILE_OPEN = 2;
}

Using final to Prevent Overriding

Methods declared as final cannot be overridden.

 
class Base {
  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!");

  }

}

If you try to compile the code above, the following error will be generated by the compiler.


D:\>javac Main.java
Main.java:7: cannot find symbol
symbol: class A
class B extends A {
                ^
1 error
Home 
  Java Book 
    Class  

Inheritance:
  1. Inheritance Basics
  2. When Constructors Are Called
  3. Using super keyword
  4. What is Method Overriding
  5. super and overridden method
  6. Method overriding vs method overload
  7. Dynamic Method Dispatch
  8. final variables