主要知识点:1. 多态实现的条件:父类引用指向子类对象子类继承父类 子类对父类的方法进行重写2. 抽象类的主要特点抽象成员只能出现在抽象类中子类继承父类之后必须对父类中的抽象方法予以实现using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
//动物类的继承实现
class Class1
{
static void Main(string args)
{
//开始实现多态:父类引用指向子类对象
//Animal animal = new Cat();
Animal a = {new Cat(), new Dog(), new Pig() };
foreach(Animal animal in a)
{
//动物叫这个方法现在已经实现了多态
animal.Bark();
animal.Drink();
animal.Eat();
}
}
}
//抽象成员只能出现在抽象类中
abstract class Animal
{
//抽象方法
public abstract void Bark(); //父类没有办法去确定子类如何实现
//这里提供的是一个普通的函数
public void Eat()
{
Console.WriteLine("Animal eat");
}
public void Drink()
{
Console.WriteLine("Animal drink");
}
}
//子类继承之后,会把父类的普通函数继承过来; 对于继承过来的抽象函数子类必须要予以实现
//一个子类继承了一个抽象的类, 那么这个子类就必须重写这个抽象父类中的所有抽象成员(重写)class Cat : Animal
{
//函数的重写
public override void Bark()
{
Console.WriteLine("cat bark");
}
}
class Dog : Animal
{
public override void Bark()
{
Console.WriteLine("dog bark");
}
}
class Pig : Animal
{
public override void Bark()
{
Console.WriteLine("pig bark");
}
}
}
评论
填写昵称与邮箱即可评论,无需登录。