Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Use the final Command in Java

Here are three ways to use the final command in Java: final class, final method, and final variables. The following Java coding examples will teach you all about the command final.

final class

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 BaseBall
{
   // members for the BaseBall class go here
}

Then no one can use the BaseBall class as the base class for another class.

When you declare a class final, all its methods are considered final as well. The final keyword isn’t required on any method of a final class.

final method

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;
    }
}

Here, the method getVelocity is declared as final. Thus, any class that uses the SpaceShip class as a base class can’t override the getVelocity method. If it tries, the compiler issues the error message (Overridden method final).

Here are some additional details about final methods:

  • Generally, you should avoid declaring final methods. Although you might think that a subclass wouldn’t need to override a method, you can’t always be sure what someone else might want to do with your class.

  • final methods execute a bit more efficiently than nonfinal methods because the compiler knows at compile time that a call to a final method won’t be overridden by some other method.

  • private methods are automatically considered final.

That makes sense; after all, a subclass can’t override a method that it can’t see.

final variables

A final variable, also called a “constant,” is a variable whose value you can’t change after it’s been initialized. For example, you might use a final variable to define a constant value, such as pi. To declare a final variable, you add the final keyword to the variable declaration, like this:

static final int WEEKDAYS = 5;

Although it isn’t required, adding the static keyword is common for final variables.

Using all capital letters for final variable names is a common convention. That way, you can easily spot the use of final variables in your programs.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.