A programmer's tale

Tuesday, July 31, 2007

making class final in fantastic way! - java.lang.Math revisited

Utility classes should be final. Utility classes generally contains static constants and static utility methods .It should not be instantiated nor it should be inherited.
Now how to make this class final and make it non instantiating? Simple question. And the answer is also as simple as the question. Declare the class with final keyword make the constructor private like the Math class in java.lang.Math.
But here the final is redundant, no need to declare the class with final, if the constructor of a class is private, then the class is implicitly final. No need to declare it with the final keyword. Look at the following code:

public class FooUtils {

private FooUtils() { }

}

Here FooUtils is our util class. If we sunclass it as:

public class Bar extends FooUtils {
}


we will get compilation error. Hence no need of final keyword. For the same reason the final keyword in java.lang.Math class in redundant.

0 Comments:

Post a Comment

<< Home