一、C#类方法的继承
子类有两种方式来重载父类中的方法
①virtual+override
②new
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Animal
{
public virtual void eat()
{
Console.WriteLine("Animal eat!");
}
public void sleep()
{
Console.WriteLine("Animal sleep!");
}
}
class Cat:Animal
{
public override void eat()
{
Console.WriteLine("Cat eat!");
}
public new void sleep()
{
Console.WriteLine("Cat sleep!");
}
}
class Program
{
static void Main(string[] args)
{
Cat c = new Cat();
c.eat();
c.sleep();
Animal cat = new Cat();
cat.eat();
cat.sleep();
}
}
}
##############
运行结果:
Cat eat!
Cat sleep!
Cat eat!
Animal sleep!
请按任意键继续. . .
##################
在不出现派生类对象的向上转型时,override和new的方法在使用上的结果是一样的。
但在将派生类cat类向上个转型时,virtual+override使用的仍是派生类中重载的方法,而使用new的方法则时调用基类的方法。
二、抽象类
在C#中,在类前加关键字abstract就可以定义一个抽象类。抽象类的定义格式:
abstract class 类名
{
//抽象类成员的定义
……
}
在抽象类中的不包含方法体的就是抽象方法。给方法的实现交给该类子类根据自己情况去实现
public abstract void 方法名{}
抽象类的方法的功能需要在派生类中用重写同名方法的方式实现。
重写的方法与抽象类中的方法的参数及其类型、方法名都应相同。
重写抽象方法在方法前面加override
总结:抽象类不可写构造函数
在派生类中一定要实现未实现的方法
抽象基类可以定义字段、属性、方法实现
抽象类只能被单一继承
三、接口
C#中,接口用来定义一种程序的协定。通俗地说,接口就是说明一个类“能做什么”,接口与抽象类非常相似,它定义了一些未实现的属性和方法。所有继承它的类都继承这些成员,在这个角度上,可以把接口理解为一个类的模板。
并且,实现接口的类或者结构要与接口的定义严格一致。
接口由方法、属性、索引器和事件的声明组成。接口中既不能包含构造函数或字段,也不能包含运算符的重载。同时,它不允许在成员上加修饰符。
接口定义如下:
interface 接口名
{
//接口成员的定义,包括方法、属性、索引及事件
……
}
应注意:
1接口中永远不包含任何实现
2不允许接口中包含任何字段
3不允许接口中包含构造函数、析构函数和静态成员;
4不允许为接口方法提供访问修饰符,指定为public
注意:实现接口的类必须实现整个接口,而不能只选择实现其中一部分。否则编译时将会产生错误。
总结:接口定义了一系列方法、属性、索引和事件,但只有声明而不提供实现
只表示一种约定
实现接口的类必须实现该接口中的所有方法
一个接口可以从多个基接口继承
一个类可以实现多个接口
接口只能定义属性、索引器、事件、和方法声明,不能包含字段。
举例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
abstract class Animal
{
public abstract void eat();
public void sleep()
{
Console.WriteLine("Animal sleep!");
}
}
interface Fly
{
void fly();
}
interface Eat
{
void eat();
}
class Cat : Animal
{
public override void eat()
{
Console.WriteLine("Cat eat!");
}
}
class Dog : Animal
{
public override void eat()
{
Console.WriteLine("Dog eat!");
}
}
class Bird : Fly,Eat
{
public void fly()
{
Console.WriteLine("Bird fly!");
}
public void eat()
{
Console.WriteLine("Bird eat!");
}
}
class Program
{
static void Main(string[] args)
{
Cat cat = new Cat();
cat.eat();
Dog dog = new Dog();
dog.eat();
dog.sleep();
Bird bird = new Bird();
bird.eat();
bird.fly();
}
}
}
运行结果:
#############
Cat eat!
Dog eat!
Animal sleep!
Bird eat!
Bird fly!
请按任意键继续. . .
################
可以看出:1.抽象基类中的抽象方法必须实现,而普通方法不一定要在派生类中实现,
而接口的方法和属性都必须实现。
2。抽象即类的派生类只能够单继承,而接口可以有多个派生类。