我只想补充大家接受的答复,因为我不同意他的结论。
我们这样做。
class Engine {
public Engine() {
init();
}
void init() {
lockDoors();
releasePressure();
tightenSeatbelts();
launchRocket();
}
...
}
现在的问题是:,可登陆Landifier。 我们应在<条码>init(功能上添加。 如果是私人的或受保护的。
- make it private <-- keeps subclasses out
- make it protected <-- allows subclasses in
Before you make a choice
首先,你应认识到,(几乎)<条码>Engine类别中的所有代码均可由一个子类取代。
- code in a public function, can easily be overridden
- code in a protected function, can easily be overridden
- code in a private function, can be replaced by overriding all methods that call it.
只有一个例外:
- you can never modify the code of a constructor
- you can never avoid a private method being called from the constructor of a super class.
- (and of course, you cannot replace a
final
method)
Protected init() - the wrong way
请说<代码>init()方法protected
确实存在陷阱。 它试图推翻它,增加以下特征。 这确实是一个错误。
class SubEngine extends Engine {
int screws = 5;
void init() {
tightenScrews();
super.init();
}
void tightenScrews() {
// this won t print 5, but it will print 0.
System.out.println("tightening " + screws + " screws");
}
}
Protected init() - the right way
因此,基本上来说,你应当仅仅解除父母的罪责,而是把执行推迟到自己的建筑人。
class SubEngine extends Engine {
int screws = 5;
public SubEngine() {
initSubEngine();
}
void init() {
// disable parent code
}
void initSubEngine() {
tightenScrews();
super.init();
}
void tightenScrews() {
// this will print 5 as expected
System.out.println("tightening " + screws + " screws");
}
}
Private init() - you may need a phonecall
现在,如果<代码>init()”方法是 private
?
- Like mentioned above, there is no way to disable the code of a parent constructor. And if init() is private you simply cannot disable it.
- You ll end up copying the entire
Engine
class, perhaps just to add 1 line of code.
- And that may not be the end of it. Even after copying your class, your copied object won t be an
Engine
meaning that you won t be able to use your EngineUtil#inspectEngine(Engine engine)
function.
- Perhaps somebody knew this in advance and made an
IEngine
interface. Then you can get away with it.
- In practice it means you ll have to take your phone, and call to that other department that made the
Engine
class, and ask them to change their code a little to take away some restrictions.
Intelligent design
还有另一种方式。 组成部分是确定变量。 他们 anything弃任何东西。 每当你们看到一个班级,在其建筑商(或采用私人方法)上,就应当有红色旗帜。
class Engine {
public Engine() {
}
public void init() {
lockDoors();
releasePressure();
tightenSeatbelts();
launchRocket();
}
// and you probably also want one of these
public void shutdown() { ... }
...
}
Intention
当然,你的意图很可能不是开放你的法典。 也许你真的不想让他人延长你的班子。 确实可以有这样的情况,即你想要把人锁住。
了解这也会使你法的测试更加困难。
任何情况都不同。