Final variables and methods in Java

final variables and methods( ):

All methods and variables can be overridden by default in subclass. If we wish to parent the sub classes from overriding the members of the super class, we can declare them as final using the keyword final as a modifier.

Eg:

final int size=100;

final void shows status( ) {------}

Making a method final ensures that the functionality defined in this method will never be altered in anyway. Similarly, the value of a final variable can never be changed. Final variables, behave like class variables and they do not take any space on individual objects of the class.

final classes:

Sometimes we may like to present a class being further sub classes for security reasons. A class that can not be sub classed is called final class. this is achieved in java using the keyword final as follows.

final class  a class{--------}

final class B class extends some class{-------}

Any attempt to inherit these classes will cause an error and the compiler will not allow it. Declaring a class final prevents any unwanted extensions to the class.

Related

Java 1829207279280639381

Post a Comment

emo-but-icon

item