Книга: C# 2008 Programmer
Overriding Interface Implementations
Overriding Interface Implementations
When implementing an interface, you can mark any of the methods from the interface as virtual
. For example, you can make the Age()
method of the Employee
class virtual so that any other classes that inherit from the Employee
class can override its implementation:
public interface IPerson {
string Name { get; set; }
DateTime DateofBirth { get; set; }
ushort Age();
}
public class Employee : IPerson {
public string Name { get; set; }
public DateTime DateofBirth { get; set; }
public virtual ushort Age() {
return (ushort)(DateTime.Now.Year - this.DateofBirth.Year);
}
}
Suppose there is a new class called Director
that inherits from the Employee
class. The Director
class can override the Age()
method, like this:
public class Director : Employee {
public override ushort Age() {
return base.Age() + 1;
}
}
Notice that the Age()
method increments the age returned by the base class by 1. To use the Director
class, create an instance of it and set its date of birth as follows:
Director d = new Director();
d.DateofBirth = new DateTime(1970, 7, 28);
When you print out the age using the Age()
method, you get 39 (2008–1970=38; increment it by 1 and the result is 39):
Console.WriteLine(d.Age()); //---39---
This proves that the overriden method in the Age()
method is invoked. If you typecast d to the IPerson
interface, assign it to an instance of the IPerson
interface, and invoke the Age()
method, it will still print out 39:
IPerson p = d as IPerson;
Console.WriteLine(p.Age()); //---39---
An interesting thing happens if, instead of overriding the Age()
method in the Director
class, you create a new Age()
class using the new
keyword:
public class Director : Employee {
public new ushort Age() {
return (ushort)(base.Age() + 1);
}
}
Create an instance of the Director
class and invoke its Age()
method; it returns 39, as the following statements show:
Director d = new Director();
d.DateofBirth = new DateTime(1970, 7, 28);
Console.WriteLine(d.Age()); //---39---
However, if you typecast d to an instance of the IPerson
interface and then use that interface to invoke the Age()
method, you get 38 instead:
IPerson p = d as IPerson;
Console.WriteLine(p.Age()); //---38---
What's happened is that the instance of the IPerson
interface (p) uses the Age()
method defined in the Employee
class.
- Chapter 5 Interfaces
- Implementing an Interface
- Interface Casting
- Chapter 15. Graphical User Interfaces for Iptables
- Displaying Interface Statistics
- QueryInterface и IUnknown
- 5.1.2. The Directory Server Interface
- Command-Line Network Interface Configuration
- Laying the Foundation: The localhost Interface
- Checking for the Availability of the Loopback Interface
- Configuring the Loopback Interface Manually
- Graphic Interface Configuration of Apache