基类实现了接口,子类还需要再实现吗?子类如何再实现该接口的方法?
基类实现了接口,子类还需要实现吗?子类再实现会覆盖基类的接口方法吗?例如:
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();
}
}
}
运行结果:
为什么iif2.Method()调用的依然是BaseClass的Method()而不是InheritClass的Method()?
[最优解释]
这是因为其实子类中的 Method 方法是一个新的方法,并不是实现的接口中定义的方法,如果你在父类的method方法前加上virtual关键字然后在子类中用 override 重写父类的方法就是你需要的效果了,最后一行就会调用子类中的方法了
[其他解释]
public interface IPrint
{
void Print();
}
public class ParentClass:IPrint
{
public virtual void Print()
{
Console.WriteLine("父类(ParentClass)打印");
}
}
public class ChildClass:ParentClass
{
public override void Print()
{
Console.WriteLine("子类(ChildClass)打印");
}
}
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成员。