|
|
Module 10: Inheritance in C# 45
Using Abstract Classes in a Class Hierarchy (continued)
interface IToken
{
string Name( );
}
abstract class Token
{
public virtual string Name( )
{ ...
}
...
}
class CommentToken: Token, IToken
{ ...
}
class KeywordToken: Token, IToken
{ ...
}
interface IToken
{
string Name( );
}
abstract class Token
{
public virtual string Name( )
{ ...
}
...
}
class CommentToken: Token, IToken
{ ...
}
class KeywordToken: Token, IToken
{ ...
}
n Example 2
Token
{ abstract }
Token
{ abstract }
IToken
? interface ?
IToken
? interface ?
Comment
Token
? concrete ?
Comment
Token
? concrete ?
Keyword
Token
? concrete ?
Keyword
Token
? concrete ?
To continue the discussion of the role played by abstract classes in a classic
three-tier hierarchy, another example is presented in the slide.
An Abstract Class That Does Not Implement an Interface
Consider Example 2, which appears on the slide. In this example, the abstract
class does not implement the interface. This means that the only way it can
supply an interface implementation to a further derived concrete class is by
providing a public method. The method definition in the abstract class is
optionally virtual, so it can be overridden in the classes as shown in the
following code:
interface IToken
{
string Name( );
}
abstract class Token
{
public virtual string Name( ) { ... }
}
class CommentToken: Token, IToken
{
public override string Name( ) { ... } // Okay
}
This shows that a class can inherit its interface and its implementation of that
interface from separate branches of the inheritance.
46 Module 10: Inheritance in C#
Comparing Abstract Classes to Interfaces
n Similarities
l Neither can be instantiated
l Neither can be sealed
n Differences
l Interfaces cannot contain any implementation
l Interfaces cannot declare non-public members
l Interfaces cannot extend non-interfaces
Both abstract classes and interfaces exist to be derived from (or implemented).
However, a class can extend at most one abstract class, so you need to be more
careful when deriving from an abstract class than you need to be when deriving
from an interface. Reserve the use of abstract classes for implementing true “is
a” relationships.
The similarities between abstract classes and interfaces are that they:
n Cannot be instantiated.
This means that they cannot be used directly to create objects.
n Cannot be sealed.
This is acceptable because if an interface is sealed, it cannot not be
implemented.
The differences between abstract classes and interfaces are summarized in the
following table.
Interfaces Abstract classes
Cannot contain implementation Can contain implementation
Cannot declare non-public members Can declare non -public members
Can extend only other interfaces Can extend other classes, which can be
non-abstract
When comparing the similarities and differences between abstract classes and
interfaces, think of abstract classes as unfinished classes that contain plans for
what needs to be finished. |
|