Abstract classes realize polymorphism and abstract class Polymorphism
I. What is polymorphism?
Multiple forms: different objects make different actions for the same operation.
Ii. Notes for abstract classes
1. abstract classes are modified using abstract
2. abstract methods can only be in abstract classes.
3. abstract classes cannot be instantiated.
4. There is no method body in the abstract method.
5. abstract classes cannot be static or Sealed Classes
6. The subclass must override all abstract methods of the parent class, unless the subclass is also an abstract class.
7. abstract classes can have common methods.
8. The constructor can be abstracted.
9. abstract methods in abstract classes are used to constrain the method form of subclass.
Iii. "instantiation" of abstract classes"
Although the abstract class itself cannot be instantiated through new, it can point the referenced object to the real object of the subclass, or it can be called indirect instantiation.
Person as parent class
public abstract class Person{
Public int Age {get; set ;}
Public string Name {get; set ;}
Public Person (int age, string name ){
This. Age = age;
This. Name = name;
}
Public abstract void Say ();
Public void Eat ()
{
Console. WriteLine ("I am a parent class ");
}
}
Student class to inherit Person
public class Student:Person{ public Student(string name,int age){
Public Student (int age, string name): base (age, name ){
This. Age = age;
This. Name = name;
}
Public override void Say ()
{
Console. WriteLine ("sub-class talk ");
}
Public void Eat (){
Console. WriteLine ("I Am a subclass ");
}
}}
When a parent class object points to a real object of a subclass, The subclass first follows the constructor of the parent class, and then assigns a value to its attribute based on the constructor of the subclass .,
Person p = new Student (18, "Zhang Yu"); p. say (); // only in this case, the parent class variable points to the subclass object and calls the subclass method. // conform to the polymorphism, the parent class and the subclass method call the subclass Method p. eat (); // if no method is involved, the method of the parent class is called by default. Student stu = (Student) p; stu. eat (); // if you want to call the unique method of the subclass, type conversion is required. It is called in java and the Console is transformed downward. readKey ();