2016-07-19

Understanding final in java

Java has a final keyword that we can use it in three places.
Final variable
When you use final with a variable, it creates a constant whose value can’t be changed once it has been initialized. Similarly final can be used to  create final methods and final classes.
For Example:
final int i=10;
final File f=new File();
final ClassName;

Final methods
A final method is a method that can’t be overridden by a subclass. To  create a final method, you simply add the keyword final to the method declaration.
For example:
public class SpaceShip
{
public final int getVelocity()
{
return this.velocity;
}
}

Guidelines about final methods:
✦ You might think that a subclass won’t need to override a method, but there’s no reason to be sure. Predicting how other people might use your class is difficult. As a result, you should usually avoid using final methods unless you have a compelling reason to.
✦ Final methods execute more efficiently than non-final methods. That’s because the compiler knows at compile time that a call to a final method won’t be overridden by some other method. The performance gain isn’t huge, but for applications where performance is crucial, it can be noticeable.
✦ Private methods are automatically considered to be final. That’s because
you can’t override a method you can’t see.

Final classes
A final class is a class that can’t be used as a base class. To declare a class as final, just add the final keyword to the class declaration:
public final class Test
{
// members for the Test class go here
}
Then, no one can use the Test class as the base class for another class.
When you declare a class to be final, all of its methods are considered to be final too. That makes sense when you think about it. Because you can’t use a final class as the base class for another class, no class can possibly be in a position to override any of the methods in the final class. Thus, all the methods of a final class are final methods.

No comments:

Post a Comment