March 15, 2007
Class provides a definition to override the interface’s abstract definitions. This is one of the ways interface is defined.
But in the following example the program Employee class doesn’t provide a definition to override the interface’s abstract definitions. The situation is same in the Animal abstract class as well. That means there is no keyword “override” when defining Work() method within the Employee class and within the Animal abstract class. Anybody explain please.
using
System;public
interface IWorking{
string Work();
}
class
Employee : IWorking{
private string name;
public Employee(string name)
{
this.name = name;
}
public string GetName()
{
return name;
}
public string Work()
{
return "I do my job";
}
}
abstract
class Animal : IWorking{
protected string name;
public Animal(string name)
{
this.name = name;
}
public string GetName()
{
return name;
}
public abstract string Work();
}
class
Dog : Animal{
public Dog(string name): base(name)
{
}
public override string Work()
{
return "I watch the house";
}
}
class
Cat : Animal{
public Cat(string name) : base(name)
{
}
public override string Work()
{
return "I catch mice";
}
}
class
DemoWorking{
public static void Main()
{
Employee bob = new Employee("Bob");
Dog spot = new Dog("Spot");
Cat puff = new Cat("Puff");
Console.WriteLine("{0} says {1}", bob.GetName(), bob.Work());
Console.WriteLine("{0} says {1}", spot.GetName(), spot.Work());
Console.WriteLine("{0} says {1}", puff.GetName(), puff.Work());
}
}
/*
Output:
Bob says I do my job
Spot says I watch the house
Puff says I catch mice
*/
Posted Mar 19, 2007, 9:24 AM
Scott LyslePosted Mar 16, 2007, 1:36 AM
The same situation exists with interfaces, there is no implementation of methods allowed in an interface and any method signature defined in an interface must be implemented in any class implementing that interface. Since such method signatures must be overriden, there is no need to supply the override keyword (as with abstract methods, if you did try to add the override keyword to a method implemention, it would not compile)
Abstract classes and interfaces are similar up to a point. In an abstract class, you can include implemented methods when those methods are not defined as abstract. Any class derived from an abstract class must implement the abstract methods but any non-abstract, implemented methods are immediately available in the derived class. Interfaces on the other hand cannot include any implemented methods nor can they define any access modifiers on any included method signatures.