In layman's OOP (ii): Polymorphism and Inheritance (inheritance)

Source: Internet
Author: User

This article is the second article of the layman's OOP, mainly talk about the topic of inheritance.

Introduction to Inheritance

In Oop, inheritance resembles the following definition:

    • Inheritance is a mechanism of OOP that is used to derive inherited predefined classes

    • In this inheritance relationship, the predefined class is the base class, and the new class is the subclass

    • Inheritance is often used to implement code reuse

    • Inheritance allows subclasses to reuse base class non-private data and methods

Implementation of inheritance

Create a console project, namedInheritanceAndPolymorphism。添加ClassA、ClassB类,并拷贝下面的代码:

x =

In Program.cs , call ClassA

Main (=

If it is running, it will be error-bound.

Error: ‘InheritanceAndPolymorphism.ClassA ' does not contain a definition for ' and Display1 no extension method ' Display1 accepting a first argumen T of type ' InheritanceAndPolymorphism.ClassA could be found

Because we do not define the method of Display1 in ClassA. Let's rewrite it to make ClassA inherit from CLASSB.

x =

Run again and the results are as follows:

ClassB Display1

ClassA can already access the DISPLAY1 function of its base class, and this simple example illustrates the beauty of inheriting a reusable base class, which illustrates the meaning of inheritance with the inheritance relationship of parent-child property.

Look at another scenario, assuming that ClassA also has a Display1 function, with the same signature as its base class:

x =

The following results are performed:

ClassA Display1

It looks like the result is right, ClassA calls its own Display1 function by default, but Visual Studio has a warning:

Warning: " InheritanceAndPolymorphism.ClassA.Display1() hides inherited member" InheritanceAndPolymorphism.ClassB.Display1() . Use the new keyword if hiding is intended.

The call to a method in C # is first the query ClassA itself has no Display1 function, and then query its base class has no Display1 function. In the case of the same function in the base class and subclass, the reality is that the base class code is too old, the subclass wants to use the same signature function, and cannot stop the same signature function of the base class, so the warning---although the logic is correct, there are some flaws in the design.

Let's try to call the base class method with the same name through base in Calssa:

x =

The results of the implementation are as follows:

ClassA Display1

ClassB Display1

This experiment shows that C # provides a base keyword that is used to invoke a function or variable (not a private type) of a base class in a descendant class.

Similarly, it is possible to invoke the Display2 of its base class in Classa.display1, as shown in the following code:

x = Main (=

The results of the implementation are as follows:

ClassA Display1

ClassB Display2

Can the function of its subclasses be called through the base class?

x = Main (=

Operation Error:

Error: ' InheritanceAndPolymorphism.ClassB does not contain a definition for ' and Display2 no extension method ' Display2 accepting a first argume NT of type ' InheritanceAndPolymorphism.ClassB could be found

The reason is that inheritance cannot implement reverse invocation, and the base class cannot invoke subclasses.

In addition to constructors and destructors, subclasses inherit some of their base classes (including private member variables and member functions, but cannot access them).

In C #, a class inherits the object type by default, object is the base class for all C # Reference types, and inheritance has transitivity, such as CLASSC inheritance from CLASSB,CLASSB inherits from ClassA, Then CLASSC can fully reuse the data and functions of the ClassA---classc inherit classa.

Can all types in C # be inherited?

 Public class  public class public class public class  ClassZ:System.Array {}
Execution Result:

' INHERITANCEANDPOLYMORPHISM.CLASSW ' cannot derive from special class ' System.ValueType '

' INHERITANCEANDPOLYMORPHISM.CLASSX ' cannot derive from special class ' System.Enum '

' Inheritanceandpolymorphism.classy ' cannot derive from special class ' System.Delegate '

' Inheritanceandpolymorphism.classz ' cannot derive from special class ' System.Array '

The results of the operation are maddening.

In C #, custom classes cannot inherit from some of the built-in classes of C #, such as,,, System.ValueType System.Enum System.Delegate System.Array , etc.

Let's look at the following example to see if a multi-class inheritance in C + + can be implemented in C #:

 Public class CLASSW {}  Public class CLASSX {}  Public class CLASSY:CLASSW, CLASSX {}

Execution Result:

Compile time Error: Class ' InheritanceAndPolymorphism.ClassY cannot has multiple base classes: ' and InheritanceAndPolymorphism.ClassW ' ClassX .

The conclusion is that C # supports only single-class inheritance and does not support the star-type inheritance relationship of C + +. To use a star inheritance relationship, use an interface implementation.

Can you implement cyclic dependency inheritance?

 Public class Classw:classy {}  Public class CLASSX:CLASSW {}  Public class CLASSY:CLASSX {}

The code logic is simple, CLASSW inherits from Classy,classx inherits from CLASSW, classy inherits from CLASSX.

But after compiling the error:

Error: Circular base class dependency involving "and InheritanceAndPolymorphism.ClassX " InheritanceAndPolymorphism.ClassW .

We come to the conclusion that C # does not allow ring-dependent inheritance.

Whether an instance object can be assigned a value
b = A =

The Program.cs code is as follows

Main (= = = =

We try to determine whether ClassA, CLASSB objects can be assigned values.

The result of the compilation is: Error

Cannot implicitly convert type ' INHERITANCEANDPOLYMORPHISM.CLASSB ' to ' Inheritanceandpolymorphism.classa ' Cannot Implicitly convert type ' Inheritanceandpolymorphism.classa ' to ' INHERITANCEANDPOLYMORPHISM.CLASSB '

Although the data member variable a data in ClassA and CLASSB is consistent, it is 100, but it is not possible to assign a value by comparing the type-reference address with the equals sign.

Let's try the inheritance relationship again:

b = A = Main (= = = = =

ClassA inherits from ClassB, and we want to be able to assign its instance object directly.

The results of the operation are as follows:

Error: Cannot implicitly convert type ' to InheritanceAndPolymorphism.ClassB ' InheritanceAndPolymorphism.ClassA .

Operation Conclusion: C # sub-class objects can be directly assigned to the base class object, the base class object needs to go down strongly. The code is modified as follows:

b = A = Main (= = = = =

So the compilation is passed.

If ClassA does not inherit from CLASSB, this strong turn will be an error in C #:

Cannot convert type ' Inheritanceandpolymorphism.classa ' to ' INHERITANCEANDPOLYMORPHISM.CLASSB '

Cannot convert type ' INHERITANCEANDPOLYMORPHISM.CLASSB ' to ' Inheritanceandpolymorphism.classa '

Conclusions of this section
    • Cannot prevent subclasses from overriding the base-like signature method

    • An inheritance relationship is a subclass of the same signature method that looks up first, then finds its base class

    • The base keyword is used by C # to call base class functions, variables in subclasses

    • The inheritance relationship is irreversible

    • In addition to constructors and destructors, subclasses inherit some of the base class

    • Custom classes inherit from the object type by default, but these types of C # cannot be inherited:,,, System.ValueType System.Enum System.Delegate System.Array , etc.

    • C # does not support inheriting from multiple classes

    • C # does not support circular inheritance

    • Sub-class objects can be assigned directly to the base class, whereas a strong turn is required

Original address: Diving in OOP (Day 2): Polymorphism and Inheritance (inheritance)

In layman's OOP (ii): Polymorphism and Inheritance (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.