1
Answer

Interfaces

Photo of progsigner

progsigner

20y
1.9k
1
I know that an interface is basically a class with all methods abstract, but can anyone offer me a good explanation as to where it would be wise to use interfaces and why? Thx

Answers (1)

0
Photo of Mykonine
NA 520 0 20y
An interface acts like a class with all methods abstract, but don't think of it as a class. Conceptually, inheriting defines characteristics that the derived class will take on, or inherit. Realizing an interface however, defines the functionality that the derived class will have. An interface defines what the class must be able to do. A base class defines how the class functions and what structure it represents. For example, from the .NET Framework itself: System.Drawing.Bitmap and System.Imaging.Metafile both inherit from Image, because they both have very similar characteristics and act very similarly. However, System.Drawing.Bitmap and System.Drawing.Font have no relation whatsoever... however they both implement System.IDisposable. The only thing they have in common is that both use unmanaged resources that must be released, and so the designers of the framework chose to make IDisposable an interface because the way Bitmaps release their resources is very different from the way Fonts release their resources, however, by implementing IDisposable, they say "I use unmanaged resources, and calling IDisposable.Dispose will release them in the manner unique to me." The interface requires nothing but that the implementing class can do what the interface says it should, and leaves how the class goes about doing it to the class. Another example is the IComparer interface, used by SortedList. You may have several dramatically different classes with dramatically different characteristics, but since the SortedList only needs a single bit of functionality, it uses an interface. If it required a common parent class, that parent class would have zero functionality and no characteristics because of the sheer range of different characteristics IComparers might have.