Inheritance is a very important feature in C#. It can allow you to achieve the polymorphisn, which is very very important feature which could help you to write the code in a good design (easy to extend).
Category
Inherit a class
Inherit a abstract class
Must implement the abstract methods in the abstract class
Can override/new the virtual methods in the abstract class
Inherit a normal class
Can override/new the virtual methods in the abstract class
Inherit an interface
Must implement all members (properties, methods, events) in the interface.
The different field
When class Student inherits class Person publicly. Those functions and members which are public and protected in class Person can be used in class Student. Functions and members which are private in class Person cannot be used in class Student.
However, if there is a public/protected function in class Person, which uses the private members of class Person. When class Student call that functions, those private members in class Person could also be used via this function.
Base function
Use base.function() in the class Student can call the functions implemented in class Person (the functions should be public/protected). This is often used when class Student rewrite the methods of class Person but still need to call the method of class Person.
About override/new keyword
Polymorphisn often happens when you declare a class Person reference, but you point it to an object instantiated from class Student.
When there is a abstract/virtual method in class Person, class Student could use override/new to rewrite that method. At this moment, call the which are rewrote can lead to charming results.
Since the abstract class can’t be instantiated, we just talked about those virtual - override/new relationship.
If the reference type and the object type is the same. Call those functions are calling the function in their own field.
If the reference type is the base class and the object type is the subclass.
If the method is declared override in subclass. Call this method from the reference is executing the method in subclass.
If the method is declared new in subclass. Call this method from the reference is executing the method in base class.
If the method is declared abstract in base class. You cannot call it except the subclass override this method.
Person person = new Person(); Person person_student = student; Console.WriteLine("--------------------"); person.ShowType(); person_student.ShowType(); student.ShowType(); Console.WriteLine("--------------------"); person.ShowName(); person_student.ShowName(); student.ShowName(); } } }
classProgram { staticvoidMain(string[] args) { Father son = new Son(); Son.DoStaticWork(); son.DoWork(); son.DoVirtualWork(); son.DoVirtualWork2(); son.DoVirtualWorkAll();