Home >Backend Development >C#.Net Tutorial >Implementing polymorphism in abstract classes in .NET
1: What is polymorphism?
Multiple forms, that is, different objects respond differently to the same operation.
2: Several notes on abstract classes
1. Use abstract modification for abstract classes
2. Abstract methods can only be located in abstract classes
3. Abstract classes cannot be instantiated
4. Abstract methods have no method bodies
5. Abstract classes cannot be static classes or sealed classes
6. Subclasses must be repeated Write all the abstract methods of the parent class, unless the subclass is also an abstract class
7. There can be ordinary methods in the abstract class
8. There can be constructors in the abstract class
9. The abstract method in the abstract class is to constrain the method form of the subclass.
Three: "Instantiation" of abstract classes
Although the abstract class itself cannot be instantiated through new, it can point the reference object to the real object of the subclass, which can also be called indirection Instantiate.
Person as the 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("我是父类"); } }
Student class inherits 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("子类说话"); } public void Eat() { Console.WriteLine("我是子类"); } }}
When the parent class object points to the real object of the subclass, the subclass first goes through the structure of the parent class Function, in the constructor of the subclass, assigns values to its properties. ,
Person p = new Student(18, "张宇"); p.Say(); //只有这一种情况,父类变量指向子类对象,调用的是子类的方法, //符合多态,父类和子类方法同名调用的是子类的方法 p.Eat(); //如果没有方法没有发生关系,则默认调用父类的方法。 Student stu = (Student)p; stu.Eat(); //如果要调用子类的特有的方法,需要进行类型转换,在java中称为,向下转型 Console.ReadKey();
The above is the detailed content of Implementing polymorphism in abstract classes in .NET. For more information, please follow other related articles on the PHP Chinese website!