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.
I was presented with this question in an end of module open book exam
Share
Inheritance is when a ‘class’ derives from an existing ‘class’. So if you have a
Personclass, then you have aStudentclass that extendsPerson,Studentinherits all the things thatPersonhas. 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 onPerson,Studentwon’t see it because its private, and private fields are not visible to subclasses.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 areadmethod, and you have aStudentwhich extendsPerson, which has its own implementation ofread, which method gets called is determined for you by the runtime, depending if you have aPersonor aStudent. It gets a bit tricky, but if you do something likethe read method on Student gets called. Thats the polymorphism in action. You can do that assignment because a
Studentis aPerson, but the runtime is smart enough to know that the actual type ofpis Student.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.