Thursday 10 November 2016

FINAL Keyword



Some basic uses of  Keyword final are:
    Using final to Define Variables: A varaible defined as final can never be changed. Final variables works like class variables and they do not take any space on individual object of the class.
Ex: class A {
final int size=100;
…….
}
    Using final to Prevent Overriding: To disallow a method from being overridden, specify final as a modifier at the start of its declaration.
Ex:class A
        {
           final void show()
           {
              System.out.println(“This is final method”);
           }
        }
class B extends A
{
void show() //ERROR: Can’t override.
            {
    System.out.println(“Not Possible”);
            }
         }

    Using final to Prevent Inheritance: To disallow a class from being inherited, specify final as a modifier at the start of its declaration.
Ex:final class A
        {
           void show()
           {
              System.out.println(“This is final method”);
           }
        }
class B extends A //ERROR: Can’t Inherit
{
void show()
            {
    System.out.println(“Not Possible”);
            }
         }

No comments:
Write comments