SitePoint Sponsor

User Tag List

Results 1 to 21 of 21
  1. #1
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,606
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)

    Abstract Class vs Interface

    What exactly is an Interface when compared to an Abstract Class? I got asked this question the other day, I can't can't say I've come across it before other than in a fleeting manner.

  2. #2
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    An interface provides the method names and parameters, but no implementation. Abstract classes provide some implementation while forcing subclasses to provide the rest. They're especially useful if you're providing a framework, where you can implement the reusable parts while the application-specific parts need to be implemented by the subclass.

  3. #3
    SitePoint Author silver trophybronze trophy
    wwb_99's Avatar
    Join Date
    May 2003
    Location
    Washington, DC
    Posts
    10,625
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    ^^^Good answer Dan.

    I should add that they are not mutually exclusive. Oftentimes, I have method signatures and such taking the Interface, but I will create an abstract class to cover alot of the default implementation where it makes sense.

  4. #4
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,606
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)
    I'm not quite sure I understand this correctly...

    The abstract class would contain the methods, and the Interface would contain method calls (and pass in values)?

    If not, what would be a good, simplified (or practical) example?

  5. #5
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    An interface contains no code whatsoever. Just method names and parameter lists. No bodies.

    An abstract class can contain code in the body of some or all of the methods.

    Neither is meant to ever be instantiated. You implement an interface, or you extend an abstract class, and instantiate that new class that does so.

    An example would be a Database interface. You've written a method in your own class that takes an object of type Database, and calls several methods on it, such as OpenConnection and ExecuteQuery. A developer who wants to use your class can provide any implementation of the Database interface as an argument and your class will work as long as it has OpenConnection and ExecuteQuery methods. They may pass in a SqlServerDatabase class object which implements Database, or a MySqlDatabase that implements Database, or an OracleDatabase that implements Database. As long as it implements the interface, your class can work with it.

  6. #6
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,606
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)
    So the idea behind all of this is to impliment a kind of encapsulation?

  7. #7
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Kinda....not really. If a class has no code, there's nothing to encapsulate.

    Interfaces are about having many classes that share functionality even though they may provide that functionality in very different ways. As long as they have the same methods, another class can interact with any of the implementations.

    Another example... take the screen you're looking at. It's got text boxes, labels, menus, buttons, various containers and scroll bars, etc. In many languages, these elements would all implement an interface for GUI elements. In order to draw the screen, the window manager just needs to call an IsVisible method on every object, then a Draw method on the objects that are visible. While a text box does not draw itself the same way a menu bar draws itself, they implement the same interface, so the window manager can use all these objects in the same way without knowing how they work.

  8. #8
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,606
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)
    Oh, wait....an Abstract class would be like the default case in a Switch case statement? Then the extended class is used to to override the abstract class's methods?

    Similar to the way it's common to override the ToString() method?

    Or am I still a bit off on this? Sorry, I'm still having a bit of trouble grasping the idea behind this concept.

    Do you happen to know of a simple code example in C#? Most of the stuff I've googled for returns highly abstract (heh) and theoretical text/ideas about definitions and implementation that just seems to confuse me more, if nothing else.

  9. #9
    SitePoint Author silver trophybronze trophy
    wwb_99's Avatar
    Join Date
    May 2003
    Location
    Washington, DC
    Posts
    10,625
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    Unfortunately, this stuff is a bit theoretical and nuanced. And has little to do with switch statements. It is one of those things that eventually just clicks one day. That said, I will give a more detailed explanation a shot.

    As Dan points out, Interfaces contain only signatures, without any implementation. Significantly, Interfaces cannot have implementation at all. They are really nothing more than a contract that is enforced in code. For example, anything that implements ITextControl (such as a TextBox or a Label) must have a Text read-write property. Furthermore, a given class can implement many interfaces, allowing one to multi-home objects if needed. And that is often needed.

    An Abstract class, on the other hand, is a fully-featured class that may or may not implement an interface. It still cannot be directly instantiated (ie--AbstractClass ac=new AbstractClasS()), but it may be passed as a type parameter. One pattern one often uses with Abstract classes is known as the Abstract Template class, where one has a super class encapsulating much functionality and exposing a standard interface while leaving hooks for developers to extend the class. Arguably the best example of this is the trusty old ASP.NET System.Web.UI.Page class. One big drawback of using Abstract classes is that, like any class, you can only inherit from a single class.

    Now for a crack at a concrete example. Since it is July 4th and the barbeque was flowing today, we are going to have to make grill objects:

    Code c#:
    public interface IGrillable
    {
            void Cook(int temp, int seconds);
    }
     
    public abstract class GrillableBase : IGrillable
        {
            #region IGrillable Members
     
            public void Cook(int temp, int seconds)
            {
                StartCookInternal(temp);
                FinishCookInternal(seconds);
            }
     
            #endregion
     
            protected abstract void StartCookInternal(int temp);
     
            protected abstract void FinishCookInternal(int seconds);
        }
    public class ShrimpSkewer : GrillableBase
        {
     
            protected override void StartCookInternal(int temp)
            {
                if (temp > 700)
                {
                    throw new FlamingException("Dude, you burned the shrimp.");
                }
            }
     
     
            protected override void FinishCookInternal(int seconds)
            {
                if (seconds > 320)
                {
                    throw new BurnedFoodException("Dude, you burned the shrimp.");
                }
            }
        }

    In this case, IGrillable provides an interface for the Grill object (not shown) to deal with. GrillableBase is an abstract base class providing a template for grillable items, like your shrimp skewer.

    Off Topic:

    Before anyone asks, yes I did grill shrimp. And they were good. Anything involving 3/4ths a pound of butter is going to be good.

  10. #10
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,606
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)
    hmm...it's starting to come together a little bit.

    How would you instantiate the class?

  11. #11
    SitePoint Author silver trophybronze trophy
    wwb_99's Avatar
    Join Date
    May 2003
    Location
    Washington, DC
    Posts
    10,625
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    Oftentimes one uses factories to instantiate concrete implementations of abstract classes. But any of the following would be legal:

    Code:
    IGrillable grillItem=new ShrimpSkewer();
    GrillableBase grillBase=new ShrimpSkewer();
    ShrimpSkewer mmmGood=new ShrimpSkewer();
    Moreover, you could pass a ShrimpSkewer to a method requiring any of the involved classes.

  12. #12
    SitePoint Addict Sojan80's Avatar
    Join Date
    May 2002
    Location
    Central WI, US
    Posts
    262
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Now this is a rocking post... I had very similar questions as Force Flow and some of the stuff covered here is helping me to get my head around it... and that grilled shrimp example just made me HUNGRY!

    By the way I have an excellent recipe for Margarita Grilled Shrimp if you're interested... no FlamingException or BurnedFoodException required! Just a hot grill, some wooden skewers and a pound or two of some lovely jmbo or extra jumbo shrimp!

  13. #13
    SitePoint Enthusiast
    Join Date
    May 2006
    Posts
    90
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'd have to say, that is one of the most entertaining examples that I've seen lately. Thanks for that

  14. #14
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,606
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)
    Alright, I stepped away from this for a bit and came back to it just to chew on it for a while (no pun intended ). I think I got my head wrapped around it a little better (the Abstract class, anyway).

    I'm still not too sure about the Interface. It seems to me that so long as you have an Abstract class, the Interface isn't really necessary since in wwb_99's instantiation example shows that you can instantiate an Abstract class without it.

    Or do I have it backwards that the Interface is needed to specify definitions (methods/attributes) in the Abstract class?

  15. #15
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Interfaces and abstract classes aren't necessarily related; you don't need to use both to use one, but it's common to see abstract classes used to partially implement interfaces.

  16. #16
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,606
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)
    Hmm...I feel like I'm going in circles here with this

    It seems like an Interface would just be unecessary code between an abstract class and whatever other class/method you're using.

    So, if you have an abstract class, and as it was mentioned earlier that an Interface enforces something (I'm not quite clear on this point). What is it enforcing and why?

  17. #17
    SitePoint Guru Galo's Avatar
    Join Date
    May 2005
    Location
    Holland!
    Posts
    852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Force Flow View Post
    Alright, I stepped away from this for a bit and came back to it just to chew on it for a while (no pun intended ). I think I got my head wrapped around it a little better (the Abstract class, anyway).

    I'm still not too sure about the Interface. It seems to me that so long as you have an Abstract class, the Interface isn't really necessary since in wwb_99's instantiation example shows that you can instantiate an Abstract class without it.

    Or do I have it backwards that the Interface is needed to specify definitions (methods/attributes) in the Abstract class?
    You cannot Instantiate an abstract class... only oncrete classes perhaps derived from an abstract base class

    interfaces are ment to have a common understanding among objects and there methods.

    like in

    car.door.open
    house.door.open
    jar.open

    they all have an open method, there's ya interface
    Business as usual is off the menu folks, ...

  18. #18
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    It'll be easier to get if you actually see them used properly in a larger application. Some open source Java apps might be a good place to start poking around.

  19. #19
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,606
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by Galo View Post
    You cannot Instantiate an abstract class... only oncrete classes perhaps derived from an abstract base class

    interfaces are ment to have a common understanding among objects and there methods.

    like in

    car.door.open
    house.door.open
    jar.open

    they all have an open method, there's ya interface
    So then using this wouldn't work? (as per the earlier example)

    Code:
    GrillableBase grillBase=new ShrimpSkewer();

    Quote Originally Posted by Dan Grossman View Post
    It'll be easier to get if you actually see them used properly in a larger application. Some open source Java apps might be a good place to start poking around.
    Maybe, althought that's not simple either since there's usually a lot more going on than just the Abstract class & Interface concept.


    I dunno...it still doesn't seem all that useful with the fractured understanding I have of the concept now.

  20. #20
    SitePoint Guru Wullie's Avatar
    Join Date
    Oct 2002
    Location
    Greenock, Scotland
    Posts
    701
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I struggled with the logic behind interfaces and read loads of tutorials online but they never made any sence to me. I ended up buying a book to hopefully get a better overview and boy did it help. The book I got was in Visual Basic.
    Visual Basic 2005: The Language

    There is "what looks like" a similar C# version available and the index shows that it covers interfaces under the chapter on inheritance. But I can't say if it will be as good as the VB book.
    Visual C# Step by Step
    ASP.NET Freelance Web Developer
    Bored? Check out my photography folio at Flickr

  21. #21
    SitePoint Wizard
    Join Date
    Feb 2007
    Posts
    1,274
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    One simple rule I have found often leads me in the "right" direction is to consider classes the "nouns" and interfaces "adjectives" (methods being the verbs).

    Consider wwbs excellent example: The class ShrimpSkewer and the interface IGrillable.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •