您的位置:首页 > 其它

接口学习,实现多态的三种方法何时使用

2015-09-08 09:49 706 查看
接口是一种规范。

只要一个类继承了一个接口,这个类就必须实现这个接口中所有的成员

为了多态。

接口不能被实例化。

也就是说,接口不能new(不能创建对象)

接口中的成员不能加“访问修饰符”,接口中的成员访问修饰符为public,不能修改。

(默认为public)

接口中的成员不能有任何实现(“光说不做”,只是定义了一组未实现的成员)。

public
interface IFlyable
{
//接口中的成员不允许添加访问修饰符 ,默认就是public
voidFly();
stringTest();
//不允许写具有方法体的函数

// string _name;
stringName
{
get;
set;
}

}

接口中只能有方法、属性(自动属性,get,set没有方法体)、索引器、事件,不能有“字段”和构造函数。

接口与接口之间可以继承,并且可以多继承。

接口并不能去继承一个类,而类可以继承接口 (接口只能继承于接口,而类既可以继承接口,也可以继承类)

实现接口的子类必须实现该接口的全部成员。

一个类可以同时继承一个类并实现多个接口,如果一个子类同时继承了父类A,并实现了接口IA,那么语法上A必须写在IA的前面。

class MyClass:A,IA{},因为类是单继承的。

显示实现接口的目的:解决方法的重名问题

什么时候显示的去实现接口:

当继承的借口中的方法和参数一摸一样的时候,要是用显示的实现接口

当一个抽象类实现接口的时候,需要子类去实现接口。

class
Program
{
static
voidMain(string[] args)
{
IFlyable fly=
new Bird();//newPerson();// new IFlyable();
fly.Fly();
Console.ReadKey();
}
}
public
class Person:IFlyable
{
public
voidFly()
{
Console.WriteLine("人类在飞");
}
}

public
class Student
{
public
voidFly()
{
Console.WriteLine("人类在飞");
}
}

public
class Bird :
IFlyable
{
public
voidFly()
{
Console.WriteLine("鸟在飞");
}
}

public
interface IFlyable
{
//不允许有访问修饰符 默认为public
//方法、自动属性
voidFly();
}

public
interface M1
{
voidTest1();
}

public
interface M2
{
voidTest2();
}

public
interface M3
{
voidTest3();
}

public
interface SupperInterface :
M1, M2,
M3
{

}

public
class Car :
SupperInterface
{

public
voidTest1()
{
throw
new NotImplementedException();
}

public
voidTest2()
{
throw
new NotImplementedException();
}

public
voidTest3()
{
throw
new NotImplementedException();
}
}

接口练习:

class
Program
{
static
voidMain(string[] args)
{
//麻雀会飞
鹦鹉会飞 鸵鸟不会飞 企鹅不会飞 直升飞机会飞
//用多态来实现
//需方法、抽象类、接口

IFlyable fly=
new Plane();//newMaQue();//new YingWu();
fly.Fly();
Console.ReadKey();

}
}

public
class Bird
{
public
doubleWings
{
get;
set;
}
public
voidEatAndDrink()
{
Console.WriteLine("我会吃喝");
}
}

public
class MaQue :
Bird,IFlyable
{

public
voidFly()
{
Console.WriteLine("麻雀会飞");
}
}

public
class YingWu :
Bird, IFlyable,ISpeak
{

public
voidFly()
{
Console.WriteLine("鹦鹉会飞");
}

public
voidSpeak()
{
Console.WriteLine("鹦鹉可以学习人类说话");
}
}

public
class TuoBird :
Bird
{

}

public
class QQ :
Bird
{

}

public
class Plane :
IFlyable
{
public
voidFly()
{
Console.WriteLine("直升飞机转动螺旋桨飞行");
}
}

public
interface IFlyable
{
voidFly();

}

public
interface ISpeak
{
voidSpeak();
}

显示实现接口:

class
Program
{
static
voidMain(string[] args)
{
//显示实现接口就是为了解决方法的重名问题
IFlyable fly=
new Bird();
fly.Fly();
Birdbird =
new Bird();
bird.Fly();

Console.ReadKey();
}
}

public
class Bird :
IFlyable
{
public
voidFly()
{
Console.WriteLine("鸟飞会");
}
///<summary>
///显示实现接口
///</summary>
void
IFlyable.Fly()
{
Console.WriteLine("我是接口的飞");
}

}

public
interface IFlyable
{
voidFly();
}

//什么时候用虚方法来实现多态?
//什么使用用抽象类来实现多态?
//什么时候用接口来实现多态?

理解:当可以写出父类,且知道父类的实现,则用虚方法来实现。反之如果不知道父类的实现,则用虚方法。如果提炼不出来父类时,则使用接口来实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: