Why and When to make a java class Final

When used in a class declaration, the “final” keyword means
the class can’t be subclassed. In other words, no other class can ever extend (inherit
from) a “final” class, and any attempts to do so will give you a compiler error.
So why would you ever mark a class “final”? After all, doesn’t that violate the
whole object-oriented (OO) notion of inheritance? You should make a “final” class
only if you need an absolute guarantee that none of the methods in that class will
ever be overridden. If you’re deeply dependent on the implementations of certain
methods, then using “final” gives you the security that nobody can change the
implementation out from under you.

You’ll notice many classes in the Java core libraries are “final”. For example, the
“String” class cannot be subclassed. Imagine the havoc if you couldn’t guarantee how
a “String” object would work on any given system your application is running on! If to make an instance of it.)

I will show you with an example. How, the havoc can be caused.


public class Test1 {

	public void runTest()
	{
		Test2 test2 = new Test2();
	
		StringType st=null;
		AnotherType at=null;
		
		test2.testMethod(st);
		test2.testMethod(at); // This is legal. But it end up returning unintended result. 
	}
	
}

class Test2
{
	protected void testMethod(StringType st)
	{		
		System.out.println(st.return2());		
	}	
}


class StringType
{
		public int return2()
		{
			return 2;
		}
}

class AnotherType extends StringType
{

	@Override
	public int return2()   //Someone intentionally overrode the function and change the logic to be different
	{
		return 50;         
	}
	
}


No responses yet

Leave a Reply