Monday, 27 August 2018

Final Variables, Methods and Classes


Final Variables, Methods and Classes

 The keyword "final" in Java is used in different ways depending on the context. We can have final methods, final classes, final data members, final local variables and final parameters. A final class implicitly has all the methods as final, but not necessarily the data members. A final class may not be extended, neither may a final method be overridden.

It is applicable for a class for the following 3 purposes:-
Ø  For the members
Ø  For the methods
Ø  For the class itself.

§  If it is applied for members they become sharable constants and can be used in other classes but it cannot be modified

§  If it is applied for methods the methods cannot be overridden in child classes.
§  If it is applied for the class itself it cannot be inherited but instances can be created.
class tree          //if you keep final before the class its not inheritable further
{
            final String head;         //it becomes readonly
            public tree()
            {
                        head="Final Keyword Concept";
            }
            final void assign() //cannot be overridden in subclass
            {
                        //head="Final"; not valid
            }
}
class node extends tree           
{
            /* void assign()
            {
                        head="Child node";
            }          */
}
class impfinal
{
            public static void main(String []args)
            {
                        node n=new node();
                        n.assign();
                        System.out.println(n.head);
            }
}
Output:
C:\>javac impfinal.java
C:\>java impfinal
Final Keyword Concept

No comments: