Final Methods

18 January 2012 By Nithya Vasudevan 230 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×
  • A final method cannot be overridden by subclasses.
  • It prevents unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class
  • private and static methods are always implicitly final, since they cannot be overridden by the sub-class.
package com.ibytecode.keywords.finaldemo;

class MyMath
{
	public final double abs(double d)
	{
		double value = (d < 0) ? -d : d;
		return value;
	}
}

class B extends MyMath
{
	//Compiler ERROR: Cannot override the final method from MyMath
	public double abs(double d) 
	{
		double value = (d <= 0.0D) ? 0.0D - d : d;
		return value;
	}
}

Tags: