Final (Java): Difference between revisions

Content deleted Content added
Bluemoose (talk | contribs)
AWB assisted clean up + tagging
Ezrarez (talk | contribs)
rewrite, wikify
Line 1:
In the [[Java programming language]], the <code>'''final'''</code> [[Keyword (computer)|keyword]] is used in several different contexts to define an entity which cannot later be changed.
{{Wikify}}
 
A '''final class''' cannot be [[Subclass (computer science)|subclassed]]. This is done for reasons of security or efficiancy. Accordingly, many of the Java standard library classes are final, for example [http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html java.lang.System] and <code>[[java.lang.String]]</code>. All [[Method (computer science)|methods]] in a final class are implicitly final.
Final keyword is used in several different contexts as a modifier meaning that what it modifies cannot be changed in any sense.
 
A '''final method''' cannot be [[Method overriding (programming)|overridden]] by subclasses. This is done for reasons of efficiancy, since the method can then be placed [[Inline function|inline]] whereever it is called.
Final classes:
For example,
 
A '''final [[variable]]''' is a [[constant]]. It must be assigned a value at [[declaration]], and the variable can later be used but not assigned a new value. Local variables (for example, variables in loops) cannot be declared final.
class Sample
[[Category:Java programming language]]
{
----
----
}
 
This means that this class will not be subclassed.It provides benfit for security and thread safety.
 
String class is defined final to prevent creating a subclass.
If you try to access the class(which is declared as final class) , then you will get a compiler error.
 
Final Method:
 
You can use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses.
 
For example, the object class has some methods as final and some are not.
 
Final Fields:
 
When a field is declared final, it is treated as a constant. and cannot be changed.
If you try to change the value,then, compile time error or an exception is generated.
 
For example:
 
class Myclass
{
final int n=10;
}
 
class My
{
public static void main(String args[])
{
Myclass m = new Myclass();
System.out.println("Constant value is "+m.n);
}
}