继承和多态之间的主要区别是什么? [英] What is the main difference between Inheritance and Polymorphism?

查看:104
本文介绍了继承和多态之间的主要区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在今天的模块开卷考试结束时遇到了这个问题,发现自己迷路了。我正在阅读 Head first Java ,两个定义似乎完全相同。我只是想知道主要的区别在于我自己的想法。我知道有很多类似的问题,但是,我没有看到哪些提供了明确的答案。

I was presented with this question in an end of module open book exam today and found myself lost. I was reading Head first Javaand both definitions seemed to be exactly the same. I was just wondering what the MAIN difference was for my own piece of mind. I know there are a number of similar questions to this but, none I have seen which provide a definitive answer.

推荐答案

继承是当阶级来自现有的阶级时。因此,如果你有一个 Person 类,那么你有一个 Student 类扩展 Person 学生 继承 所有的东西。您在Person中的字段/方法上放置的访问修饰符有一些细节,但这是基本的想法。例如,如果您在 Person 上有一个私有字段,那么 Student 将看不到它,因为它是私有的,私有的字段对于子类是不可见的。

Inheritance is when a 'class' derives from an existing 'class'. So if you have a Person class, then you have a Student class that extends Person, Student inherits all the things that Person has. There are some details around the access modifiers you put on the fields/methods in Person, but that's the basic idea. For example, if you have a private field on Person, Student won't see it because its private, and private fields are not visible to subclasses.

多态性处理程序如何决定应该使用哪种方法,具体取决于它具有什么类型的东西。如果您有一个 Person ,它有一个读取方法,并且您有一个 Student 扩展 Person ,它有自己的读取的实现,确定调用哪个方法由运行时为您服务,具体取决于您是否具有 Person Student 。它有点棘手,但是如果你做了类似的事情

Polymorphism deals with how the program decides which methods it should use, depending on what type of thing it has. If you have a Person, which has a read method, and you have a Student which extends Person, which has its own implementation of read, which method gets called is determined for you by the runtime, depending if you have a Person or a Student. It gets a bit tricky, but if you do something like

Person p = new Student();
p.read();

调用学生上的读取方法。这就是多态性的作用。您可以执行该分配,因为 Student Person ,但运行时很聪明足以知道 p 的实际类型是学生

the read method on Student gets called. Thats the polymorphism in action. You can do that assignment because a Student is a Person, but the runtime is smart enough to know that the actual type of p is Student.

注意详情不同的语言。例如,你可以在javascript中继承,但它与它在Java中的工作方式完全不同。

Note that details differ among languages. You can do inheritance in javascript for example, but its completely different than the way it works in Java.

这篇关于继承和多态之间的主要区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆