本文摘自PHP中文网,作者迷茫,侵删。
一:什么是多态?
多种形态,既不同的对象对于同一个操作做出的相应不同。
二:.抽象类的几个注意事项
1,抽象类使用abstract修饰
2,抽象方法只能位于抽象类中
3,抽象类不能实例化
4,抽象方法没有方法体
5,抽象类不能是静态类或者密封类
6,子类必须重写父类的所有抽象方法,除非子类也是抽象类
7,抽象类中可以有普通的方法
8,抽象了中可以有构造函数
9,抽象类中的抽象方法就是为了约束子类的方法形式。
三:抽象类的“实例化”
虽然抽象类本身不能通过new进行实例化,但他可以将引用对象指向子类的真实对象,也可以称为间接实例化。
Person作为父类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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类去继承Person
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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( "我是子类" );
}
}}
|
父类对象指向子类的真实对象时,子类首先走的是父类的构造函数,在走子类的构造函数,给其属性赋值。,
1 2 3 4 5 6 7 8 9 10 11 | Person p = new Student(18, "张宇" );
p.Say();
p.Eat();
Student stu = (Student)p;
stu.Eat();
Console.ReadKey();
|
以上就是.NET中抽象类实现多态的详细内容!
相关阅读 >>
c#中ini配置文件的图文代码详解
.net中抽象类实现多态
.net winform实现在listview中添加progressbar的方法
c# 加密类工具实例分析
为 jenkins 配置 .net 持续集成环境
.net 1.x中的委托实例详解
.net winform的gdi双缓冲的实现方法_实用技巧
c#中序列化的使用总结
c#中noto sans字体支持韩文的实例教程
详细介绍.net中的性能改进
更多相关阅读请进入《.net》频道 >>
清华大学出版社
作者:[美]克里斯琴·内格尔(Christian Nagel)著。出版时间:2019年3月。
转载请注明出处:木庄网络博客 » .NET中抽象类实现多态