{"id":1380,"date":"2013-02-16T13:46:02","date_gmt":"2013-02-16T18:46:02","guid":{"rendered":"http:\/\/unitstep.net\/?p=1380"},"modified":"2013-02-16T13:46:02","modified_gmt":"2013-02-16T18:46:02","slug":"java-final-finally-and-finalize","status":"publish","type":"post","link":"https:\/\/unitstep.net\/blog\/2013\/02\/16\/java-final-finally-and-finalize\/","title":{"rendered":"Java: final, finally and finalize"},"content":{"rendered":"
One of the most popular Java interview “screener” questions is often, “What is the difference between final<\/strong>, finally<\/strong> and finalize<\/strong>?”<\/em> In fact, it occurs so much that one should probably have the answer memorized. But knowing when to use these features is better than just knowing what they mean.<\/p>\n <\/p>\n When used on a class, This is mainly done for reasons of security and consistency: If you have a class whose methods you count on to provide predictable results, you may want to prevent that class from being extended so that someone cannot substitute a subclass that behaves differently to a consumer that expects your original class. The same may go for certain methods on a class.<\/p>\n But generally, you should not be marking classes\/methods as In particular, you should not be marking classes\/methods as One reason you shouldn’t<\/em> refrain from marking a method as When used on variables, As opposed to the use of Furthermore, the use of Some people may think that the use of final variables is superfluous, but I think it’s a good defensive programming technique. This article<\/a> sums up my viewpoints nicely.<\/p>\n As opposed to the Here is a contrived example:<\/p>\n In this example, we initialize the Here is how that code could also look in Java 7:<\/p>\n As you can see, the amount of “boilerplate” is reduced as we don’t need to have an explicit As opposed to The
final<\/code> keyword – classes and methods<\/h2>\n
final<\/code> prevents the class from being extended. Similarly, when
final<\/code> is used on a method, that method cannot be overridden in any subclass. <\/p>\n
final<\/code> unless you have a compelling argument for it. The reason is that using
final<\/code> may unnecessarily constrain the design and hamper future developers who may have a legitimate reason for wanting to extend your class. Though I prefer composition over inheritance, it’s not a choice I would want to force on everyone else, nor do I believe it’s always the right choice.<\/p>\n
final<\/code> just for some perceived performance benefit. In many cases you won’t gain a thing performance wise, but will be unnecessarily be constraining your design.<\/p>\n
final<\/code> is for mockability; mocking frameworks like JMockit<\/a> allow you to easily mock out final<\/em> methods, so don’t let that affect your design decisions.<\/p>\n
The
final<\/code> keyword – variables<\/h2>\n
final<\/code> essentially means that the variable can only be assigned once. For class\/static members, this is when the class is loaded; for instance members, this is when an instance of the class is created; for local variables, it is usually when the variable is declared. Method parameters can also be declared as
final<\/code>.<\/p>\n
final<\/code> on classes\/methods, I usually like using
final<\/code> for most variables, as it can decrease the complexity of code by decreasing the chances for state changes. Once you know that a local variable is
final<\/code>, if it’s primitive, you can be sure its value won’t change; if it’s an object, you can be sure you’ll always be dealing with the same object.<\/p>\n
final<\/code> on member variables ensures that you know they’ll be assigned once and only once: At object creation. <\/p>\n
finally<\/h2>\n
final<\/code> keyword, which is completely optional and not strictly necessary to use, you should almost always be using the
finally<\/code> keyword in Java when dealing with closeable resources. (This is true before Java 7, as Java 7 introduces some nice syntactic sugar that can remove the need to use
finally<\/code>)<\/p>\n
InputStream inputStream = null;\r\ntry {\r\n inputStream = new FileInputStream(new File(\"TEST.XML\"));\r\n final int read = inputStream.read();\r\n \/\/ Do other stuff with the stream...\r\n} finally {\r\n if (null != inputStream) {\r\n inputStream.close();\r\n }\r\n}<\/code><\/pre>\n
inputStream<\/code> within a
try<\/code> block. If anything goes wrong with reading from the stream, an exception will be thrown (which we don’t handle here, for brevity) but before it is allowed to propagate, the code within the
finally<\/code> block will be executed, ensuring that if the stream has been opened, it will be closed. This will prevent a resource leak from happening.<\/p>\n
try (final InputStream inputStream = new FileInputStream(new File(\"TEST.XML\"))) {\r\n final int read = inputStream.read();\r\n \/\/ Do other stuff with the stream...\r\n}<\/code><\/pre>\n
finally<\/code> block anymore. This is known as a “try-with-resources” statement<\/a>, where an object that implements
Closeable\/AutoCloseable<\/code> is declared and initialized with the
try<\/code> statement and automatically closed no matter what the outcome of the statements within the
try<\/code> block. I would suggest using this unless your code needs to be JDK 6 compatible. <\/p>\n
finalize()<\/h2>\n
final<\/code>, which you may use and
finally<\/code>, which you will certainly have to use in JDK 6 and below, you will almost never need to implement or override
Object.finalize()<\/code><\/a>.<\/p>\n