Header Ads

Access Modifiers in java | Final Modifier in java

Final Modifier in java

Final Modifier in java


Final Modifier:

Final is the modifier which can be applied for classes, methods and variables.


Final Methods:

1. Whatever the methods parent has by default available to the child.

2. If the child is not allowed to override any method, that method we have to declare with final in parent class. That is final methods cannot overridden.


Example:

Program 1:


class Parent

{

public void property()

{

 System.out.println("car+gold+land+cash");

}


public final void marriage()

{

 System.out.println("lmn"):

}

}





Program 2:


class child extends Parent

{

public void marriage()

{

 System.out.println("abc");

}

}


OUTPUT:

       javac Parent.java      -->(run on cmd)

       javac child.java       -->(run on cmd)

       Compile time error. -->(output on cmd)


       Here,marriage() in child cannot override marriage() in Parent;

       overridden method is final







Final Class:


If a class declared as the final then we cannot creates the child class that is inheritance concept is not applicable for final classes.


Example:


Program 1:


final class Parent

{


}



Program 2:


class child extends Parent

{


}



OUTPUT:


    javac Parent.java    -->(run on cmd)

    javac child.java     -->(run on cmd)

    Compile time error.  -->(output on cmd)



Important Note: Every method present inside a final class is always final by default whether we are

declaring or not. But every variable present inside a final class need not to be final.




Example:


final class parent

{

static int x=10;

static {

x=999;

}

}



The main advantage of final keyword is that we can achieve security.

Whereas the main disadvantage is we are missing the key benefits of oops concept:

polymorphism (because of final methods), inheritance (because of final classes) hence if there is no specific requirement then never recommended to use final keyboard.


An Inspirational quote: 

"Greatness only comes before hustle in the dictionary."
 



Steps to Subscribe my blog in 15 secs:
1. Enter your mail id in "Subscribe" box.
2. Enter Captcha for verification.
3. A mail will be received with link in your mail id.Just Click on link  and  then Done .Thank you for subscribing :)

No comments

Note: Only a member of this blog may post a comment.