Total Pageviews

Thursday, January 20, 2011

Final Keyword

FInal Keyword in java - Final keyword can be used to make a class,method or a
field as final. When used with class it means that the class cannot be used by
a subclass ie no inheritance (like String class). When a method is declared as
final it means that the method cannot be overrided by any subclass. Technically
any method if used by a constructor must be declared as final to disallow it
being over ridden causing data corruption (as method can be over- rided).

There are two meanings when a variable is declared as final. Consider the
following example:
final String str ="amit";

This means that the value of str remains unchanged in the entire program.A good
approach for this is use capital letters for variable name.

final Date date;

The above declaration means that the date object reference is constant ie it
cannot refer to any other object once initialized. But it does not states that
the value of date cannot be changed. We can always use methods of date class to
change the values.Consider the example:
final Date d;
d= new Date();
d.setHours(12);
System.out.println("hours"+d.getHours());
d.setHours(15);
System.out.println("hours"+d.getHours());

The value changes to 15. But if you try to reassign the object d to another
memory location,java gives error as the object is declared final.

Thumb Rule: Use final with primitive or immutable data types. Other objects
declared as final leads to confusion.

No comments:

Post a Comment