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

标签 java

我一直在阅读 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/

相关文章:

java - spring boot如何在目标中创建jar文件而无需在pom中添加插件

java - Eclipse 创建的 Web 服务出错

java - 如何在 jtable 行中插入 jcombobox 以获得多个值

java - Spring-JDBC batchUpdate 未提交更改。这是一个已知错误吗?

java - fragment UI 元素为空

Java:当表示为某种编码的字节时获取字符串的长度

java - 如何使用maven构建一个自包含的可执行jar?

java - java spring如何自定义@NotNull验证错误信息

java - 无法使用反射API访问java中的私有(private)方法

java - InvokeLater() - 一次就够了吗?