Another useful modifiers in regard to controlling class member usage is the final modifier. The final modifier specifies that a variable as a constant value or that a method cannot be overridden in a subclass. The final modifier makes class member is the final version allowed for the class.For creating symbolic constant you can use final modifier.
final public int CENT=100;//constantthe above is similar to const variable in c++,they must always be initialized upon declaration and their value can't change any time afterward.
final boolean FLAG=true;
Three usage of final are:
1. A final class cannot be inherited.
2. A final method cannot be changed by subclass (or) overriding.
3. A final data member cannot be changed after initialization(constant).
Final Class:
final class X{ } class Y extends X { void print() { System.out.println("inside block y"); } public static void main(String args[]) { Y a=new Y(); a.print(); } }
Output:
Example-2:
Final Variable:
class X { final int i=10;// constant variable void print() { i=20; } public static void main(String args[]) { X a=new X(); a.print(); } }
Output:
0 comments:
Post a Comment