基类实现了接口,子类还需要再实现吗?子类如何再实现该接口的方法?
基类实现了接口,子类还需要实现吗?子类再实现会覆盖基类的接口方法吗?例如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
interface IInterface
{
void Method();
}
class BaseClass : IInterface
{
public void Method()
{
Console.WriteLine("BaseClass Method()...");
}
}
class InheritClass : BaseClass
{
public void Method()
{
Console.WriteLine("Inherit Method()...");
}
}
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
InheritClass ic = new InheritClass();
bc.Method();
ic.Method();
IInterface iif = new BaseClass();
iif.Method();
IInterface iif2 = new InheritClass();
iif2.Method();
Console.ReadKey();
}
}
}
}
}
ParentClass p = new ParentClass();
p.Print();
ChildClass c = new ChildClass();
c.Print();
IPrint i = new ParentClass();
i.Print();
i= new ChildClass();
i.Print();
Console.ReadKey();
[其他解释]
也许你注意到,编译时VS警告你这样会覆盖父类的方法,其实默认就是
class InheritClass : BaseClass
{
new public void Method()
{
Console.WriteLine("Inherit Method()...");
}
}
这样InheritClass.Method()本身就不是BaseClass成员,也就不是IInterface成员。