Wednesday, 18 November 2009

Use of final

final


final can be used in multiple places

final variable

final method

final class


final variable

  • Value of a variable whose declaration is preceded by keyword final , cannot be changed during program execution
  • If any part of code tries doing that , it results in error
  • They must be given some value at the time of decaration, compiler does not give them default value as it does for non final variables
example

                          final int number = 5 ;

final method

  • When we want that a method should not be overridden by a subclass , precede it's declaration with final
  • If a subclass tries to override a method declared as final , it results in error
example

final void sample ()

{
// code
}

final class

  • When we want that a class should not be extended by a subclass , precede it's declaration with final
  • If a subclass tries to extend a class declared as final , it results in error
example

final class test

{
// methods and properties
}