Java: Final Variables, Methods and Final Classes
December 13, 2010 2 Comments
In my last post I have shared about JButton and JMenuItem ActionListener.
Here I have shared about Final Variables, Methods and Final Class.
By default all methods and variables can be overridden in subclasses.
It is possible to prevent the subclasses from overriding the members of super class; we can declare them as final using the keyword final as a modifier.
The value of a final variable can never be changed.
Ex : final int age=45;
Making a method final ensures that the functionality defined in this method will never be altered in any way.
Ex: final void age()
It may happen that we want to prevent a class being subclassed for security reasons or for any other reason related to our software . We can do it easily using final class. So, the class that cannot be subclassed is called a final class.
Ex: final class age
If we try to inherit the above class will cause an error and the compiler will not allow it. It prevents any unwanted extension to the class.