Inheritance and polymorphism

xiaoxiao2021-03-06  14

An important feature is inheritance, what is inheritance? What does it work? The main purpose of inheritance is to expand the functionality and method of the original class, to enhance or improve the attributes and methods defined by the original class. For example, we have dogs, but there are still a lot of dogs, such as Bomei dogs, St. Bernard, Chai dog, etc. Objects will have some properties and methods that are not used by other objects, such as the way to save people in Snow Bernard, but Bomei does not need to save people in the snow, so in Bome This method does not need in the dog's object

So we can define some subclasses below the dog. These subclasses will inherit the attributes and methods of the dog class, and then add some of their own properties and methods, Or modify the method that is not used in this class. We are used to call the inherited class as the parent class, and the inherited class is subclass.

When using the polymorphism, there must be three points must be mainly, the first particular instance is the particular instance. It does not describe the original instance because of different representations, such as a small Black bear, you can call it an animal, but in fact it is still an object that is generated by a bear, rather than an animal class. The second is when you look at the small black as an animal, then you can only use and access the properties and methods provided by the animal class. That is to say that the bear has a new method, for example, sleep for 16 hours, but you don't know if it is an animal, how can you know that it is 16 hours? So when you look at it as animals, you cannot use a child. Third, if the parent class is overwritten, the method of subclass is executed when you call this method as a parent class. Or than the sleeping method, such as setting 8 hours, the bearings are inherited and modified, for example, to extend the sleep time of 16 hours. This reason is very simple, after an object is generated, then until the dead, it will always be an example of the class when it generates it. So the bear will sleep for 16 hours, no matter what you take it, it will perform its own modified method.

转载请注明原文地址:https://www.9cbs.com/read-49331.html

New Post(0)