问题描述
最终类和私有的类构造函数之间的区别是什么。
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?
推荐答案
最后的类不能扩展。它阻止此
A final class cannot be extended. It prevents this
final class FinalClass {
}
// and later
class ExtendedClass extends FinalClass { // ERROR
}
这对于像String这样的东西很有用 - 你不希望有人能够覆盖String最常用的对象之一的逻辑,并且能够,我不知道,添加网络并发送您使用的所有字符串。
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
通常这样的工作方式是这样的:java.lang.Math )
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(...) { }
}
b $ b
或者它最终像这样工作// Integer这实际上是
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. :-)
这篇关于有一个类作为final和有一个类构造函数作为私有有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!