Java final keyword

In this chapter you will learn:

  1. What is Java final keyword
  2. What are final variables
  3. How to use final to prevent overriding

Description

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

Final variables

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

Prevent overriding

Methods declared as final cannot be overridden.

 
class Base {//  w ww .  ja va2s .co m
  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.

Next chapter...

What you will learn in the next chapter:

  1. What is abstract class
  2. How to create abstract class
  3. Example - abstract class
  4. A demo for using abstract methods and classes