Re: Abstract class or interface?
- From: Jon Shemitz <jon@xxxxxxxxxxxxxxxxx>
- Date: Mon, 02 May 2005 00:37:18 -0700
> what are some conceptual reasons to use one over the other?
One way to look at it is "breadth" vs "depth".
You don't know much about the objects that implement your interface,
and this gives you a lot of implementation flexibility. With an
interface, you don't care what else the object can do, so long as it
implements your interface. To use a hackneyed example, imagine an
interface IText { string Text { get ; set ; } }
- you don't care if an IText reference is a desktop Form or other
Control, a web control, or a custom class. An IText[] array could
freely mix all three - every IText has a Text property, regardless of
how it's implemented or what else the object can do.
Conversely, with an abstract class, you can know things about your
objects that you can't know about an interface. (For example, you
can't mark an interface method as [Obsolete], nor is there any way to
insist that all interface implementations be [Serializable].) You can
have constructors, protected members, fields, attributes. Descendants'
implementation of various methods can rely on non-public features of
the base class.
An interface is appropriate when you don't care about anything besides
what can be expressed in an interface. Or when you need to treat a
wide variety of objects in a consistent manner. An abstract base class
is appropriate when you have a tightly coupled family of objects, that
need (or can benefit from) access to protected fields and helper
methods.
[At the risk of confusing the issue, a set of classes that implement
an interface might all descend from a common base class (besides
System.Object, that is) that provides some standard implementations of
all or part of the interface.]
As a rule of thumb, use an interface unless there's a really obvious
reason to use an abstract base class. Information Hiding Is Your
Friend.
--
www.midnightbeach.com
.
- References:
- Abstract class or interface?
- From: Brett
- Abstract class or interface?
- Prev by Date: Re: What is [MTAThread] & why doesn't VB have it?
- Next by Date: Re: Invoke Error
- Previous by thread: Re: Abstract class or interface?
- Next by thread: Re: Abstract class or interface?
- Index(es):
Relevant Pages
|