First blog, first article in China 3.0
Today, I reviewed the object-oriented thinking. In order to strengthen my memory, I wrote down my review.
First, the first object-oriented feature is encapsulation, inheritance, and polymorphism.
1: Encapsulation
What is encapsulation? In my simple understanding, encapsulation is packaging. In order to solve the maintenance and management of large projects.
2: Inheritance
Understanding: inheritance is actually a matter of concept. We use a class library as the original template and expand other templates based on it.
Advantage: Code redundancy is solved.
Feature: Transmission
This involves calling constructor methods. When a subclass calls its own constructor, it first initializes the constructor of the parent class, but does not initialize an object of the parent class, as to why the constructor of the parent class will be initialized, I understand that the fields of the parent class will be initialized first.
Lee's conversion principle:
Sub-classes can be assigned to parent class objects.
Parent class objects can be forcibly converted to corresponding subclass objects.
1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. text; 5 using System. threading. tasks; 6 7 namespace inherits 8 {9 public class BaseFun10 {11} 12 public class Fun: BaseFun13 {14} 15 class Program16 {17 static void Main (string [] args) 18 {19 // sub-classes can be assigned to the parent class 20 BaseFun bs = new Fun (); 21 // The parent class can be forcibly loaded into the corresponding sub-class 22 Fun fun1 = (Fun) bs; 23 // is 24 Console. writeLine (fun1 is BaseFun); // True25 Console. writeLine (fun1 is Fun); // True26 Console. writeLine (fun1 is object); // True27 // as use 28 Fun fun2 = fun1 as Fun; 29 Console. writeLine ("OK"); 30 Console. read (); 31} 32} 33}
3: Polymorphism
Definition: multiple States of an object displayed when the same method is called
A: rewrite the base class method to realize polymorphism: the parent class is called uniformly, and the Child class is implemented.
B: Realize polymorphism by hiding the base class method.
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace polymorphism {public class BaseFun {public virtual void Eat () {Console. writeLine ("I am BaseFun") ;}} public class Fun: BaseFun {public override void Eat () {Console. writeLine ("I'm Fun") ;}} public class Fun1: BaseFun {public new void Eat () {Console. writeLine ("I am Fun1") ;}} class Program {static void Main (string [] args) {BaseFun bs = null; bs = new Fun (); bs. eat (); Fun1 fun1 = new Fun1 (); fun1.Eat (); BaseFun bs1 = fun1; bs1.Eat (); Console. read ();}}}