gpt4 book ai didi

java - 静态工厂相对于构造函数的劣势

转载 作者:行者123 更新时间:2023-12-01 14:07:33 24 4
gpt4 key购买 nike

关闭。这个问题需要details or clarity .它目前不接受答案。












想改善这个问题吗?通过 editing this post 添加详细信息并澄清问题.

7年前关闭。




Improve this question




我正在学习 Effective Java。第一项为构造函数上的静态工厂方法提供了令人信服的案例。

我没有得到第一个缺点

The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.



为什么我需要继承具有静态工厂方法的类,因为静态方法不能被继承?

有人可以解释一下。

最佳答案

假设您有一个名为 Person 的类:

class Person {
public static Person createWithFirstName(String firstName) {
return new Person(firstName, null, null);
}
// etc. - more factory methods

// private constructor
private Person(String firstName, String lastName, String nickname) { }

// useful method
public String getDisplayName() { }
}

这一切都很好。但是现在您还需要一个名为 Programmer 的类,你突然意识到程序员也是人!

但突然之间,你不能只是
class Programmer extends Person { }

Person没有任何 public构造器。

关于java - 静态工厂相对于构造函数的劣势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19733789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com