Thursday, July 18, 2013

12. Final keyword on variables, method and classes

1. Final variables:

"The values in the variables declared as final cannot be modified or changed"

Example

public class testbox2 {
final int b;
testbox2(int input) <<-- Constructor
{
b=input; << -- Final vari can be assigned only in constructor other than during declaration/initialization.
}

public static void main (String[] args)
{
testbox2 tb2= new testbox2(45); << -- Passing parameter to constructor allowed
tb2.b=123; << -- Illegal Not permitted
System.out.println(tb2.b);

}
}


2. Final Methods:

"Final methods cannot be overridden"

Note: Final method is available to the subclass it only can't be overridden.

Example

Public myClass {

final myMethod(){
/* --- ---
   --- --- */
}

}

Public mySubClass extend myClass{

myMethod<< -- Illegal Not permitted - Final method cannot be overridden
/* --- ---
   --- --- */
}
}

3. Final Classes:

"Final class cannot be inherited"

Example

Public final myClass {
}

mySubClass extends myClass{ << -- Illegal Not permitted - Final class cannot inherit
}


No comments :

Post a Comment