从一个旧类派生一个新类的机制称为继承
多态性是指对类的成员方法的调用形成不同的实现方式
多态性分为静态多态和动态多态两种。方法重载属于静态多态,方法覆盖(方法重写)属于动态多态
而方法覆盖必须满足这些条件:
方法覆盖必须满足以下条件:
1.派生类的方法名称、参数和返回类型必须与基类的方法名称、参数和返回类型一致
2.派生类的方法不能缩小基类的访问权限
3.方法覆盖只存在于派生类和基类之间,在用一个类中方法只能重载不能被覆盖
4.基类的静态方法不能被派生类的覆盖为非静态方法
5.基类的非静态方法不能被派生类覆盖为静态方法
例如:
class Polymorphism
{
public static void Main()
{
Ianimal dog = new Dog();
dog.叫();
Ianimal cat = new Cat();
cat.叫();
Ianimal cabrite = new Cabrite();
cabrite.叫();
Console.ReadKey();
}
}
public interface Ianimal
{
void 叫();
}
public class Dog : Ianimal
{
public void 叫()
{
Console.WriteLine("狗在叫");
}
}
public class Cat : Ianimal
{
public void 叫()
{
Console.WriteLine("猫在叫");
}
}
public class Cabrite : Ianimal
{
public void 叫()
{
Console.WriteLine("蜥蜴不会叫");
}
}
---------------ASP.Net+Android+IOS开发、.Net培训、期待与您交流! -----------