ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java: The Final Keyword

Updated on February 16, 2011

Introduction

For better or worse, designers of the Java programming language elected to use the keyword final in multiple contexts. In this tutorial we will examine three popular applications of the keyword: final classes, final methods, and final properties. We present code snippets illustrating the application of each construct and we discuss software engineering scenarios in which these keywords may be useful.

A final class cannot be used as a base class. A final method in a base class cannot be overridden in a derived class. A final property cannotprogrammatically be assigned a new value. Obviously each use of the keyword has a slightly different meaning and is used in a different context. With some study and practice, programmers and analysts should have no problem applying and deciphering code that uses these keywords.

Final Classes in Java

Generally speaking, any Java class can be used as a base class, unless it is declared with the keyword final. Consider the difference between these two class declarations:

public class myClass{
// ...
}

final public class myFinalClass{
//...
}

Given the above code snippets, here are examples of what to do and what not to do:

// This will compile
public class myDerivedClass extends myClass {
//...
}

// This will not compile!
public class myDerivedClass extends myFinalClass {
//...
}

In line 7 of the the preceding code snippet, an attempt is made to inherit from the class called myFinalClass, which was declared in line 5 of the earlier snippet to be a final class. By definition, a final class cannot be used as a base class. The code will generate a build error along the lines of "The type myDerivedClass cannot subclass the final class FinalClass".

This error can be remedied in two different ways:

  1. Remove the reference to FinalClass in the declaration of myDerivedClass, or
  2. Remove the final keyword from the declaration of FInalClass.

Final Methods in Java

Next, we move on to a discussion of final methods in Java. Like final classes, the keyword final can be applied to a method, but the meaning is slightly different.

A method declared as final cannot be overridden in a derived class. Consider the following code snippet for an illustration of this keyword.

/**
 * Demonstrate a final class method
 * @author nicomp
 */
public class FinalClassMethod {
/**
 * This method can be inherited but
 * not overridden in the derived class. 
 * (no polymorphism)
 */
	final public void HelloWorld() {
		System.out.println("Hello World");
	}
/**
 * This class method can be overridden because
 *  it's not declared as final.
 * @param msg The message that will be written to stdout
 */
	public void HelloWorld(String msg) {
		System.out.println("Hello World: " + msg);
	}
}

In line 11 of the preceding code snippet, the method HelloWorld() is declared as final. This keyword prevents any class that inherits from the FinalClassMethod class from overriding the definition of HelloWorld(). Attempting to do so will result in a compilation error.

Refer to the following code snippet for examples of what to do and what not to do:

// This class attempts to override a method
//  in its' base class that has been declared
//  as final. A compilation error will result.

public class Oops extends FinalClassMethod {
	public void HelloWorld() {
		System.out.println("Hello from the Oops class");
	}

}

Line 6 of the previous code snippet will be the site of a compilation error long the lines of "Cannot override the final method from FinalClassMethod." This error can be removed by removing the final keyword from the declaration of the HelloWorld() method in the base class.

Note that the HelloWorld(String s) method in the base class can be overridden.

Final Class Properties

Applying the final keyword to a class property causes that property to be treated as a program constant. This is analogous to the const keyword in C++.

In the following code snippet we illustrate how to declare a class property as final and how to initialize it in the constructor:

/**
 * Illustrates a class member that cannot be changed
 * @author nicomp
 *
 */
public class FinalClassMember {
// This class member cannot be assigned a new value
// It's final, but it needs to be initialized somehow
	final private int width; 
	
	
/**
 * The default constructor.
 */
	public FinalClassMember() {
//		We can assign the 'final' member a value here.		
//	 	This provides the initialization
		width = 42;	
	}
/**
 * @return The width of the object
 */
	public int GetWidth() {return width;}

/**
 * 	
 * @param width The new value of the width of the object
 * @return The new value
 */
	public int SetWidth(int width) {

//		Compilation error: 
//		The final field FinalClassMember.width
//		 cannot be assigned		
		this.width = width; // oops!
		return width;
	}
}

Line 35 of the previous code snippet will generate a compilation error along the lines of "The final field FinalClassMember.width cannot be assigned." This error can be remedied in one of two ways:

  1. Remove line 35 from the method
  2. Remove the final keyword from the declaration of the property, width.

Practical applications of the Final Keyword in Java

We have introduced and discussed three different applications of the final keyword in Java. it is interesting to consider why these keywords might be useful to the programmer. All programmers are expected to have a thorough understand of the nuances of their language(s) of choice in order to write the most robust and maintainable programs. Using the final keyword correctly can certainly make Java code 'safer' in that programming errors may be reduced.

As discussed above, a class declared as final cannot be used as a base class. This strategy will prevent programmers from accidentally inheriting the class and adding functionality that may not be appropriate. In most circumstances, a class is meant to be used as a base class, but in the narrow situations where a class is logically 'complete', it's a good programming practice to prevent other developers from using it as a base class.

As discussed above, a method declared as final cannot be overridden in a derived class. The method is still inherited by the derived class, but a method with the same signature cannot be included in the derived class. This will reduce the possibility of the derived class replacing crucial logic in the base class. Of course, the derived class can still completely ignore the final method in the base class, but logic errors cannot be detected by the Java compiler.

As discussed above, a class property declared as final cannot be assigned a new value. This is the Java technique for creating program constants. Constants are a staple of any programming language. Any class property that should not change should be declared as a final: it's a simple and effective programming convention that is easy to follow. For example:

private final int PI = 3.1415927;

The value of PI should remain constant throughout the class. By declaring PI as final, potential programming errors are eliminated. Any attempt to assign a new value to PI will result in a compilation error that is obvious and simple to remedy.

Conclusion

The Java programming language uses the keyword final in multiple contexts. We have introduced and discussed three different applications of the keyword: final classes, final class methods, and final class properties.

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)