01接口
1 接口就是一个规范、能力。(苹果为什么做接口不统一?占用量大,侵占市场)
2只要一个类继承一个接口,这个类必须实现这个接口中的所有成员。
3 注意点
1)可以没有返回值和返回值,
2)接口中的成员不可以添加访问修饰符,默认为public
3)无方法体
4)接口不可以写字段
5)只能有方法、属性、索引器
4)接口不可以实例化
5)接口中的成员不能有任何实现(“光说不做”,只是定义了一组未实现的成员,子类去实现)
6)接口与接口之间可以继承,并且可以多继承,类与类之间不可以多继承(单根性)
7)接口不可以继承与类,只能继承接口
8)如果一个类继承了接口有继承父类,语法上先写父类再写接口
02 虚方法
1)步骤
1)将父类的方法标记为虚方法,使用关键词virtual,这个函数可以被子类重新写一遍
03抽象类
1)当父类中的方法不知道如何实现的时候,可以考虑将父类写成抽象类,将方法写成抽象方法。
2)抽象类标记Abstract,抽象成员必须标记为anstract,并且不能有任何实现;
3)抽象成员必须在抽象类中,抽象类中可以有非抽象成员,用在继承;
4)抽象类不能实例化;
5)子类继承抽象类,必须将抽象类中的抽象成员重写;
c#语法特征
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01接口语法特征
{
class Program
{
static void Main(string[] args)
{
IFlyable fly = new Person();
fly.Fly();
IFlyable fly1 = new Brid();
fly1.Fly();
Console.ReadKey();
}
}
public class Person : IFlyable
{
public void Fly()
{
Console.WriteLine("人类在飞!");
}
}
public class Brid:IFlyable
{
public void Fly()
{
Console.WriteLine("鸟在飞!");
}
}
public interface IFlyable
{
void Fly();
}
}
接口练习
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02接口练习
{
class Program
{
static void Main(string[] args)
{
}
}
public class Bird
{
int _winding;
}
public interface IFlyable
{
void Fly();
}
public class MQ : Bird, IFlyable
{
public void Fly()
{
Console.WriteLine("麻雀会飞!");
}
}
public class QE : Bird
{
}
public class YW : Bird, IFlyable
{
public void Fly()
{
Console.WriteLine("鹦鹉会飞!");
}
}
public class ZSFPlane : IFlyable
{
public void Fly()
{
Console.WriteLine("直升灰机会飞!");
}
}
}
显示实现接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03显示实现接口
{
class Program
{
static void Main(string[] args)
{
IFlyable fly = new Bird();
fly.Fly();
Bird bird = new Bird();
bird.Fly();
Console.ReadKey();
}
}
public class Bird : IFlyable
{
public void Fly()
{
Console.WriteLine("鸟会飞!");
}
void IFlyable.Fly()
{
Console.WriteLine("恢复费");
}
}
public interface IFlyable
{
void Fly();
}
}