Final classes

18 January 2012 By Nithya Vasudevan 535 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×
  • You can declare an entire class final — this prevents the class from being sub classed.
    • Final class prevents inheritance.
  • Trying to extend a class that is marked as final will result in compiler error.
  • Accordingly, many of the Java standard library classes are final, for example java.lang.System and java.lang.String.
  • All methods in a final class are implicitly final.
  • Use final class for safety, when nobody should change your method implementation.
  • Final class can never be improved or specialized by another programmer.
//FINAL CLASS
final class Animal
{
	/*
	 1. All methods in a final class are implicitly final.
	 */
}
//Error - Cannot subclass the final class
class Cat extends Animal { }

Compiler Error: The type Cat cannot subclass the final class Animal

Tags: