c#基础知识第十二节

继承和多态

继承(继承具有传递性)

//(父类)
class Animal
{
public string Name
{
get;
set;
}
public void shout()
{
Console.WriteLine("动物叫");
}
}
//(子类)
class Dog : Animal
{
public void printName()
{
Console.WriteLine("名字 :"+Name);
}
}
class Program
{
static void Main(string[] args)
{
//实例化子类
Dog d = new Dog();
d.Name = "沙皮狗";
d.printName();
d.shout();
Console.ReadKey();
}
}

如果拥有父类的话,在调用自身构造方法之前会先调用父类的构造方法。

隐藏基类(父类)方法

class Animal //父类
{
//父类方法
public void Shout()
{
Console.WriteLine("动物叫!");
}
}
//子类
class Dog:Animal
{
//子类方法
public new void Shout() //使用new关键字来隐藏基类方法
{
Console.WriteLine("狗叫!");
}
}
class Program
{
static void Main(string[] args)
{
Dog d = new Dog();
d.Shout();
Console.ReadKey();
}
}

密封(sealed)不能被继承

object类

class program

{
static void Main(string[] args)
{
Console.WriteLine(42.ToString());
int i = 42;
Console.WriteLine(i.ToString());

Console.ReadKey();

}
}

多态:同一方法在不同类中(希望父类方法在子类中得到一定的改进)

class Animal //父类
{
//父类方法
public virtual  void Shout()//使用virtual关键字来修饰要重写的父类方法
{
Console.WriteLine("动物叫!");
}
}
//子类
class Dog:Animal
{
//子类方法
public override  void Shout() //使用override关键字来修饰,重写父类方法
{
Console.WriteLine("狗叫!");
}
}

里氏转换原则

1.Animal an=new Dog();

2.Aniaml an=new Dog();

  Dog dog=(Dog)an;//将父类变量an强制转换为子类类型dog

base关键字

专门用于在子类中访问父类的成员

 

posted @ 2017-10-17 16:34  你的斗志并没有失去  阅读(140)  评论(0编辑  收藏  举报