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();
}
}