Deep understanding of OOP (2): Polymorphism and inheritance (inheritance), deep understanding of oop

Source: Internet
Author: User

Deep understanding of OOP (2): Polymorphism and inheritance (inheritance), deep understanding of oop

This article is the second article of OOP, mainly about inheritance.

  • Deep understanding of OOP (1): Polymorphism and inheritance (polymorphism during initial binding and compilation)

  • Deep understanding of OOP (2): Polymorphism and inheritance (inheritance)

  • Deep understanding of OOP (III): Polymorphism and inheritance (dynamic binding and Runtime polymorphism)

  • Deep understanding of OOP (4): Polymorphism and inheritance (abstract class in C)

  • In-depth understanding of OOP (5): access modifier in C # (Public/Private/Protected/Internal/Sealed/Constants/Static and Readonly Fields)

  • Deep understanding of OOP (6): enumeration (practical method)

  • Deep understanding of OOP (7): attributes (practical methods)

  • Deep understanding of OOP (8): indexer (practical method)

  • Deep understanding of OOP (9): Events (in-depth understanding)

 

Introduction to inheritance

In OOP, inheritance has the following definitions:

  • Inheritance is an OOP mechanism used to derive the predefined classes.

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

  • Inheritance is often used for code reuse.

  • Inherit data and methods that allow subclass reuse of non-private base classes

 

Inheritance implementation

Create a Console project namedInheritanceAndPolymorphism. Add the ClassA and ClassB classes and copy the following code:

ClassA:

   class ClassA
     {
        
     }

ClassB:

    class ClassB
    {
        public int x = 100;
        public void Display1 ()
        {
            Console.WriteLine ("ClassB Display1");
        }
        public void Display2 ()
        {
            Console.WriteLine ("ClassB Display2");
        }
    }
 

In Program.cs, call ClassA

class Program
    {
        static void Main (string [] args)
        {

            ClassA a = new ClassA ();
            a.Display1 ();
        }
    }
If it runs, it will definitely report an error.

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


Because we have not defined the Display1 method in ClassA. Below we rewrite, so that ClassA inherits from ClassB.

 

ClassA:

  class ClassA: ClassB
    {
        
    }

ClassB:

class ClassB
    {
        public int x = 100;
        public void Display1 ()
        {
            Console.WriteLine ("ClassB Display1");
        }
        public void Display2 ()
        {
            Console.WriteLine ("ClassB Display2");
        }
    }
 

Run again, the result is as follows:

ClassB Display1


ClassA can already access the Display1 function of its base class. This simple example illustrates the beauty of inheriting a reusable base class. The following picture illustrates the meaning of inheritance with the inheritance relationship of parent and child property.

 

Let's look at another scenario. Suppose ClassA also has a Display1 function with the same signature as its base class:

class ClassA: ClassB
    {
        public void Display1 ()
        {
            System.Console.WriteLine ("ClassA Display1");
        }
    }

ClassB:

class ClassB
    {
        public int x = 100;
        public void Display1 ()
        {
            Console.WriteLine ("ClassB Display1");
        }
        public void Display2 ()
        {
            Console.WriteLine ("ClassB Display2");
        }
    }
The results after execution are as follows:

ClassA Display1


It seems that the result is correct. 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 was intended.


The call to the method in C # is to first query ClassA for the Display1 function, and then query the base class for the Display1 function. In the case that the same function appears in the base class and the subclass, it exists in the real project. The code of the base class may be too old. The subclass wants to use the function with the same signature and cannot stop the function with the same signature of the base class Such a warning-although the logic is correct, this design has some flaws.

 

Let's try to call the method of the same name of the base class through base in CalssA:

 

ClassA:

  class ClassA: ClassB
    {
        public void Display1 ()
        {
            Console.WriteLine ("ClassA Display1");
            base.Display1 ();
        }
    }

ClassB:

class ClassB
    {
        public int x = 100;
        public void Display1 ()
        {
            Console.WriteLine ("ClassB Display1");
        }
        public void Display2 ()
        {
            Console.WriteLine ("ClassB Display2");
        }
    }
The results are as follows:

ClassA Display1


ClassB Display1


This experiment shows that C # provides the base keyword, which is used by subclasses to call base class functions or variables (non-private types) in inheritance.

 

Similarly, it is also possible to call Display2, its base class, in ClassA.Display1. The code is as follows:

/// <summary>
   /// ClassB: acting as base class
   /// </ summary>
   class ClassB
    {
        public int x = 100;
        public void Display1 ()
        {
            Console.WriteLine ("ClassB Display1");
        }
        public void Display2 ()
        {
            Console.WriteLine ("ClassB Display2");
        }
    }

    /// <summary>
    /// ClassA: acting as derived class
    /// </ summary>
    class ClassA: ClassB
    {
        public void Display1 ()
        {
            Console.WriteLine ("ClassA Display1");
            base.Display2 ();
        }
    }

    /// <summary>
    /// Program: used to execute the method.
    /// Contains Main method.
    /// </ summary>
    class Program
    {
        static void Main (string [] args)
        {
            ClassA a = new ClassA ();
            a.Display1 ();
            Console.ReadKey ();
        }
    }
The results are as follows:

ClassA Display1


ClassB Display2


 

Is it possible to call the functions of its subclasses through the base class?

/// <summary>
   /// ClassB: acting as base class
   /// </ summary>
   class ClassB
    {
        public int x = 100;
        public void Display1 ()
        {
            Console.WriteLine ("ClassB Display1");
        }
    }

    /// <summary>
    /// ClassA: acting as derived class
    /// </ summary>
    class ClassA: ClassB
    {
        public void Display2 ()
        {
            Console.WriteLine ("ClassA Display2");
        }
    }

    /// <summary>
    /// Program: used to execute the method.
    /// Contains Main method.
    /// </ summary>
    class Program
    {
        static void Main (string [] args)
        {
            ClassB b = new ClassB ();
            b.Display2 ();
            Console.ReadKey ();
        }
    }
Running error:

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


The reason is that inheritance cannot implement reverse calls, neither the base class can call subclasses.

 

In addition to the constructor and destructor, the subclass inherits some of its base class (including private member variables and member functions, but only inaccessible)

 

In C #, a class inherits the object type by default, and object is the base class of all reference types in C #; at the same time, inheritance is transitive, such as ClassC inherits from ClassB, ClassB inherits from ClassA, then ClassC can fully reuse ClassA data And the function --- ClassC inherits ClassA.

 

Can all types in C # be inherited?

public class ClassW: System.ValueType
   {
   }

   public class ClassX: System.Enum
   {
   }

   public class ClassY: System.Delegate
   {
   }

   public class ClassZ:
System.Array
   {
   }
Results of the:

'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 result of the operation is crazy

 

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

 

In the following example, let's take a look at whether multi-class inheritance in C ++ can be implemented in C #:

 public class ClassW
 {
 }

 public class ClassX
 {
 }

 public class ClassY: ClassW, ClassX
 {
 }
Results of the:

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


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

 

So can circular dependency inheritance be implemented?

public class ClassW: ClassY
    {
    }

    public class ClassX: ClassW
    {
    }

    public class ClassY: ClassX
    {
    }
The code logic is very simple, ClassW inherits from ClassY, ClassX inherits from ClassW, and ClassY inherits from ClassX.

But after compiling it gives an error:

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


We have come to the conclusion that circular dependency inheritance is not allowed in C #.

Whether the instance object can be assigned

ClassB:
public class ClassB
    {
        public int b = 100;
    }

ClassA:

    public class ClassA
    {
        public int a = 100;
    }
Program.cs code is as follows

public class Program
    {
        private static void Main (string [] args)
        {
            ClassB classB = new ClassB ();
            ClassA classA = new ClassA ();
            classA = classB;
            classB = classA;
        }
    }
We try to determine whether the objects of ClassA and ClassB can be assigned.

The result of the compilation is: wrong

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


Although the data member variable a in ClassA and ClassB has the same data, both are 100, but the equal sign is used here to compare the type-reference address, so it cannot be assigned.

 

Let's try inheritance again:

public class ClassB
    {
        public int b = 100;
    }

    public class ClassA: ClassB
    {
        public int a = 100;
    }

    /// <summary>
    /// Program: used to execute the method.
    /// Contains Main method.
    /// </ summary>
    public class Program
    {
        private static void Main (string [] args)
        {
            ClassB classB = new ClassB ();
            ClassA classA = new ClassA ();
            classA = classB;
            classB = classA;
        }
    }
ClassA inherits from ClassB, and we hope to directly assign its instance object.

The results are as follows:

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


Operation conclusion: C # subclass objects can be directly assigned to base class objects, which need to be forced down. The code is modified as follows:

public class ClassB
    {
        public int b = 100;
    }

    public class ClassA: ClassB
    {
        public int a = 100;
    }

    /// <summary>
    /// Program: used to execute the method.
    /// Contains Main method.
    /// </ summary>
    public class Program
    {
        private static void Main (string [] args)
        {
            ClassB classB = new ClassB ();
            ClassA classA = new ClassA ();
            classB = classA;
            classA = (ClassA) classB;
        }
    }
This compile passed.

If ClassA does not inherit from ClassB, this forced transfer will be reported as an error in C #:

Cannot convert type 'InheritanceAndPolymorphism.ClassA' to 'InheritanceAndPolymorphism.ClassB'


Cannot convert type 'InheritanceAndPolymorphism.ClassB' to 'InheritanceAndPolymorphism.ClassA'


Conclusion of this section
Cannot prevent subclasses from overwriting base class with same signature method
Inheritance relationship is the same signature method of subclasses, and then the base class
The base keyword is used by C # to call base class functions and variables in subclasses
Inheritance is irreversible
In addition to the constructor, destructor, 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 inheritance from multiple classes
C # does not support cyclic inheritance
Subclass objects can be directly assigned to the base class, otherwise they need to be forced
 

Translation address: http://www.cnblogs.com/powertoolsteam/p/Diving-in-OOP-Polymorphism-and-Inheritance-Part.html

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

Related Article

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.