What exactly is the difference between a final class and having a class constructor as private.
I know both can't be subclassed(correct me if i am wrong). Is their any difference?
The main difference between private and final class is that you can inherit from a private class in the same class but extending the final class is prohibited by the Java compiler. Though you can not create a sub-class of a private class outside of the class they are declared, similar to the final class.
private is about accessibility like public or protected or no modifier. final is about modification during inheritance. private methods are not just accessible from the outside of the class. final methods can not be overridden by the child class.
The child class inherits all the members of the superclass except the constructors. In other words, constructors cannot be inherited in Java, therefore, you cannot override constructors. So, writing final before constructors make no sense. Therefore, java does not allow final keyword before a constructor.
No, a constructor can't be made final. A final method cannot be overridden by any subclasses.
A final class cannot be extended. It prevents this
final class FinalClass {
}
// and later
class ExtendedClass extends FinalClass { // ERROR
}
This is useful for things like String - you wouldn't want someone to be able to overwrite the logic of String, one of the most commonly used Objects, and be able to, oh I don't know, add networking and send all the strings back you use. It's possible to do if you can extend String.
A private constructor cannot be called outside the class.
class PrivateCons {
private PrivateCons() {
}
}
// later
PrivateCons pc = new PrivateCons(); // ERROR
Often this ends up working like this: (java.lang.Math is a good example)
class FuncLib {
private FuncLib() { } // prevent instantiation
public static void someFunc(...) { }
public static int anotherFunc(...) { }
}
Or it ends up working like this // Integer does this actually
class VerySpecial {
private static Map<String,VerySpecial> cache;
public static VerySpecial generate(String data) {
VerySpecial result = cache.get(data);
if(result == null) {
result = new VerySpecial(data);
cache.put(data,result);
}
return result;
}
private String data;
private VerySpecial() { }
private VerySpecial(String data) { this.data = data}
}
When you extend a class, your constructor by default attempts to call the default (no argument) constructor. If that is private, then you must explicitly call a non-private constructor when you extend it. If you have no non-private constructors to call you won't be able to extend it. Thanks for comments for pointing this out. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With