除了减少冗余代码之外,继承的最佳用途是什么?
继承的最佳用途是什么,除了减少冗余代码之外!
让我们举个例子
A类:基类
B类:子类
和 C 类。
CLASS A
^
| And CLASS C
|
|
CLASS B
我可以通过继承在 B 类中使用 A 类的方法。
同样,我可以在 C 类中使用 A 类的方法,
通过创建 A 类的实例。(假设 A 是公共的)
使用继承,只减少创建新的对象/实例?
请帮助我更好地理解!
What is the best use of Inheritance, other than it will reduce redundant code!
Let us take an example
Class A:Base Class
Class B:Sub Class
and Class C.
CLASS A
^
| And CLASS C
|
|
CLASS B
i can use methods from Class A, in Class B by inheritance.
in the same i can use the methods from Class A, in Class C,
by creating instance of Class A.(say A is Public)
using inheritance, only reduce creating new Object/Instance?
Plz help me to better understand!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一个很大的好处是多态性。如果类 B 和 C 都继承自 A,那么每当需要类型 A 的对象时,都可以用 B 类型的对象或 C 类型的对象来替换它。假设在 B 和 C 中重写了相应的方法,则这样根据您传递的对象获得不同的行为非常方便。
示例:
那么:
A great benefit is polymorphism. If classes B and C both inherit from A, then whenever an object of type A is required, it can be replaced by either an object of type B or an object of type C. Assuming the corresponding methods are overriden in B and C, this is very handy to get different behavior depending on which object you pass.
Example:
Then:
继承的要点是多态性:允许其他类使用
ClassB
的实例,只知道它可以用作ClassA
。我最喜欢的例子是流 - 例如,我可以轻松地编写一个采用
InputStream
和OutputStream
的copyStream
方法,仅使用在这些方法上声明的方法类型。然后我可以将 FileInputStream 复制到 ByteArrayOutputStream ,或使用网络相关的流等,所有这些都无需更改 copyStream 方法中的任何代码。The main point of inheritance is polymorphism: to allow other classes to use an instance of
ClassB
knowing only that it can be used as aClassA
.My favourite example is streams - I could easily write a
copyStream
method taking anInputStream
and anOutputStream
for example, using only the methods declared on those types. Then I could copy aFileInputStream
to aByteArrayOutputStream
, or use network-related streams etc, all without changing any of the code in thecopyStream
method.使用继承的主要原因是不删除冗余代码。
继承和所有可能的魔法是 OOP 的关键、中心点。扩展类不仅允许您使用其功能,还可以修改(通过多态性)并添加更多功能。
The main reason to use inheritance is not to remove redundant code.
Inheritance and all magic made possible is a key, central point in OOP. Extending a class doesn't only allow you to use its functionality, but also modify (by polimorphism) and add more functionality.
差异在于需要了解将类 B 传递到作用于类 A 的函数的能力。从这个意义上说,B 是 A 的类型,其中类 C 具有或拥有 A。差异很小,仅在某些情况下才有意义。
这并不是说代码中的差异通常是明确的。通常,当人们真正想要所有权时,他们会继承,有时当一个对象确实是其他事物的一种类型时,他们就会拥有所有权。
The difference comes with the need to understand the ability to pass class B into functions that act on class A. In this sense B is-a type of A where class C has or owns A. The difference is small and only significant in certain circumstance.
That is not to say that the difference is often made explicit in code tbh. Often people will inherit when they really want ownership and sometimes they do ownership when an object really is-a type of something else.