Working with final classes and methods

Working with final classes and methods


Posted in : Core Java Posted on : October 7, 2010 at 4:10 PM Comments : [ 0 ]

This section describes about the final classes and methods in java.

Working with final classes and methods

The 'final' keyword has three uses :

First, it can be used to create a named constant. The other two uses are given below :

Using final method to prevent method overriding

Sometimes you need to prevent method overriding from occurring. For this specify 'final' as a modifier at the start of method's declaration.

Example :

class X{
   final void display(){
      System.out.println("Inside a final method.");
  }
}

class Y extends X{
   void display(){  // Error can't override.
      System.out.println("Error");
    }

}

Above code will give error on compilation due to final method overriding.

Using final to Prevent Inheritance

Sometimes you need to prevent a class from being inherited. For this , precede the class declaration with final. Declaring a class as final implicitly declares all of it's methods as final too ,which prevent class from being inherited.

final class X{
   //  .....
}
// The following class is illegal.

class Y extends X{
   void display(){  // Error!! can't subclass X
      System.out.println("Error");
    }

}

It is illegal for Y to inherit X since X is declared as final.

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics