·  JAVA – Syntax – Keywords – final

 

- Info:

  - final class can not be inherited (through extend keyword).

  - final variable means that it is constant, it can be initialized inside constructor.

  - final method can not be overriden thorugh inheritance

 

- Example:

  - This example defines simple class with defined constructor and single property and method.

  - Create JAVA Console Application Test.java

 

    Test.java

    public class Test{ 

      public static void main(String[] args) { 

        Car fiat = new Car();

            fiat.startEngine(); 

            //fiat.topSpeed = 200;  //The final field Car.topSpeed cannot be assigned.

      }

    }

   

    final class Car {

      final public int topSpeed = 100;

      final void startEngine() { System.out.println("Accelarating to " + topSpeed); }

    }

   

    //EXTENDING FROM FINAL CLASS IS NOT ALLOWED.

    //class BMW extends Car {} //The type BMW cannot subclass the final class Car

   

    //OVERRIDING FINAL METHOD IS NOT ALLOWED.

    class BMW extends Car {    //Remove final from class Car for this to work.

      //void startEngine() { System.out.println("Explode"); } //Cannot override final method from   Car

    }