Code Encyclopedia-Inheritance

Source: Internet
Author: User

Inheritance is the relationship of Is-a. Once saw someone used to reuse the inheritance: there is a base class, which wrote a lot of common methods, many classes inherit from this class, this cooking is to has-a with is-a to achieve.

The concept of inheritance is that a class is a special type of another class.

Liskov substitution principle: Derived classes must be able to be used through the interface of the base class, and the user does not need to know the difference between the two. This principle is felt to ensure that the semantics of inheritance are not changed, so that the complexity of inheritance can be controlled.

Some principles for inheritance:

    • If multiple classes share data rather than behavior, you should create a common object (HAS-A) that these classes can contain.
    • If multiple classes share behavior rather than data, you should let them inherit from the common base class and define the common subroutine in the base class, which is easy to confuse: The premise is to see if it is a is-a relationship, if not, or not to use inheritance, but to put these shared behaviors into common objects. The common object is then referenced.
    • If multiple classes share data and share behavior, you should let them inherit from a common base class, defining common data and subroutines in the base class
    • When you want to control an interface in a base class, use inheritance when you want to control the interface yourself, using the containing.
    • Avoid making the inheritance system too deep, not more than three layers, and the number of subcategories suggested 7+-2
    • When a large number of switch, case, you can consider using inheritance, using a polymorphic fitness case type check.

Code Encyclopedia-Inheritance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.