![]() |
![]() |
Java Interface | |
Java Class vs Interface | |
Java Multiple Inheritance | |
Java Nested Interface |
Java Packages | |
Java Built in packages | |
Java Package Access Specifiers |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
The final keyword allows us to prevent same thing defining again or modifying later in the program.
The keyword final has 3 uses for making
By declaring a variable with final keyword the access is restricted for making inheritable. The value of final variable never be changed in the program. They always behave like a class variables and they do not take any space on indivisual object of the class.
final type variable_name = constant_value;
final int max = 300;
Program to show use of final variables in the program.
class Base { final int max = 300; Base() { max = 400; // produces an error } } class Derived extends Base { Derived() { max = 500; // produces an error } public static void main(String args[]) { Derived d1 = new Derived(); } }
In above program we have declared final variable as max in the Base class. We have tried to change the value of it inside the Base class as well in derived class, Produces same error.
The method which is defined as final it ensures that the functionality defined in the method will never be changed.
final type method_name() { ... ... }
final int show() { final method code ... }
class Base { final void display() { System.out.println("I'm from base class"); } } class Derived extends Base { void display() // produces an error { System.out.println("I'm from Derived class"); } public static void main(String args[]) { Derived d1 = new Derived(); d1.show(); } }
In above example, we have declared the display method as final in the Base class. When we tried to redefine in the Child class then we get an error.
To prevent the classes being further subclasses is called as a final class. It is Necessary for the security reasons in java.
final class className { ... ... }
final class First { ... ... }
final class Base { void Message() { System.out.println("I'm from base class"); } } class Derived extends Base // produces an Error { void Message() { System.out.println("I'm from Derived class"); } public static void main(String args[]) { Derived d1 = new Derived(); d1.Message(); } }