Ii. inheritance
Inheritance occurs because there are too many duplicate code in the object class, a parent class is established to resolve the problem, and this part of the code is placed in the parent class and inherited by subclasses. Subclasses inherit all the attributes of the parent class, and can define new attributes.
If the subclass inherits from the parent class, the subclass has properties and functions that are not private to the parent class, and the subclass has its own properties and capabilities, that is, subclasses can extend the properties and functionality that the parent class does not have, and subclasses can implement the functionality of the parent class in their own way (method overrides).
Class Animal //Parent class { protected string name = ""; field, modifier means subclass can inherit public Animal (string name) //constructor { this.name = name; } protected int shoutnum = 3; Property and its setting method public int Shoutnum { get { return shoutnum; } Set { shoutnum = value; } } Public virtual string Shout () //Parent class method, note that the added virtual modifier represents the method allowing the quilt class to override { return ""; }}
Class Cat:animal //Subclass, inherited from parent class {public Cat (string name): Base (name) //Inherit constructor of parent class, constructor cannot be inherited, can only be called {} Public override string Shout () //override method of parent class { string result = ""; for (int i = 0; i < shoutnum; i++) result + = "Meow"; Return "My name is" + name + "+ result; }}
The advantages of Inheritance: code sharing, avoid duplication, can make it easier to modify or extend the implementation of the inheritance;
The disadvantage of inheritance: The parent class becomes the subclass, inheritance destroys the wrapper, and the parent implementation details are exposed to subclasses, which is obviously a strongly coupled relationship between classes and classes.
Summary: The application of inheritance is when two classes have a ' is-a ' relationship, which is fully contained.
Three, polymorphic
Polymorphism means that different objects can perform the same action, but to execute with their own implementation code, the overriding method of the parent class and subclass in Section Two is a polymorphic representation.
The virtual keyword can be used in scopes: properties, events, methods, and indexers, but fields cannot be virtual. Subclasses can choose to override the parent class's methods with the override keyword.
private void Button1_Click (object sender, EventArgs e) //Client call { Animal cat; Declare the parent class when declaring cat = New Cat ("small Microphone"); instance to instance as subclass Cat. Shoutnum = 5; Performs a subclass of the overridden method MessageBox.Show (cat. Shout ()); }