继承和多态的主要区别是什么? [英] What is the main difference between Inheritance and Polymorphism?
问题描述
今天在模块开卷考试结束时向我提出了这个问题,我发现自己迷路了.我正在阅读 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 Java
and 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
, 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
,它有一个 read
方法,你有一个 Student
扩展了 Person
,它有自己的 read
实现,调用哪个方法是由运行时决定的,具体取决于您是 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 上的 read 方法被调用.这就是行动中的多态性.你可以做这个作业,因为 Student
is a 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屋!