gpt4 book ai didi

java - 多态不就是封装的一个效果吗?

转载 作者:行者123 更新时间:2023-11-30 06:10:43 25 4
gpt4 key购买 nike

我一直在阅读 Herbert Schildt 的 Java“完整引用”第 8 版。

第 2 章第 22 页有这一段。

The final attribute, polymorphism, is clearly reflected in the ability of car manufacturers to offer a wide array of options on basically the same vehicle. For example, you can get an antilock braking system or traditional brakes, power or rack-and-pinion steering, and 4-, 6-, or 8-cylinder engines. Either way, you will still press the brake pedal to stop, turn the steering wheel to change direction, and press the accelerator when you want to move. The same interface can be used to control a number of different implementations

现在,在封装第 18 页的同一章中,

Further, what occurs inside the transmission does not affect objects outside the transmission. For example, shifting gears does not turn on the headlights! Because an automatic transmission is encapsulated, dozens of car manufacturers can implement one in any way they please. However, from the driver’s point of view, they all work the same. This same idea can be applied to programming.

Isn't the only reason that car manufacturer can vary these ( antilock braking system or traditional brakes, power or rack-and-pinion steering, and 4-, 6-, or 8-cylinder engines) because the rest of the systems are encapsulated from these and won't be affected by changing them?

如果我哪里做错了,我很抱歉。

我的问题是,

封装真的和多态有因果关系吗?

最佳答案

通过封装,您的汽车由各种部件制成。您可能有 4x 车轮、车头灯等,它们都包含在“Car”中。汽车不必知道如何点亮,它只是要求车头灯通过开关来做到这一点。

通过多态性,您可以用不同的系统(实现)替换一个系统,而不会被注意到。例如,您可以将车头灯更换为 LED 车头灯。它们是一个完全不同的系统,但您仍然只需按下相同的开关,它们就会启动。

所以我想你可以说汽车中包含的灯是封装,能够在不改变你正在使用的接口(interface)的情况下将它们切换到不同的实现是多态性。

此外,正如一般性一样,封装通常使用相同的代码——您通常不会在运行时切换封装类的实现方式,除非您还结合了多态性——多态性是封装类可能更改代码的方式/实现以及运行时的数据。

关于java - 多态不就是封装的一个效果吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50295895/

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