locked
Example of Abstract Class and Interface RRS feed

  • Question

  • User-110406894 posted

    I am creating some documentation for junior devs to provide an example of Abstract Class vs. Interface. I would like to get some feedback on my sample code - does this explain the topic, is the code correct, anything I can improve on, etc? Thank you kindly for your assistance!

    In the sample code below, the scenario is that we need a DollarBill class to process a CashPayment. The DollarBill class will share some functionality with a CoinCurrency class so we need to implement an IMoney interface.

    public interface IMoney
    {
         void Save();
    }
    
    abstract class PaperCurrency : IMoney
    {
        protected int amount;
        public abstract int Amount { get; set; }
    
        public void Save()
        {
            /* do things here */
        }    
    
        public abstract void CashPayment();
    }
    
    abstract class CoinCurrency : IMoney
    {
        protected int amount;
        public abstract int Amount { get; set; }
    
        public void Save()
        {
            /* do things here */
        }    
    
        public abstract void RollCoins();
    }
    
    public class DollarBill : PaperCurrency
    {
        Amount = 1;   
    
        public override void CashPayment()
        {
            /* do things here */
        }
    }
    
    public class Quarter : CoinCurrency
    {
        Amount = 25;   
    
        public override void RollCoins()
        {
            /* do things here */
        }
    }



    Thursday, May 14, 2015 10:37 AM

Answers

  • User-434868552 posted

    @sbenhoff`   welcome to forums.asp.net

    you will like find this post useful:  http://forums.asp.net/post/5219333.aspx 

    also:

    For questions like "Difference between interface and abstract class", Google and/or your favourite search engine(s) is very helpful:

    http://lmgtfy.com/?q=Difference+between+interface+and+abstract+class 

    EDIT:

    How can I use interface and abstract class better?

    at http://forums.asp.net/post/4792310.aspx, Mike Brind wrote "Abstract classes can include implementations of methods which can be over-ridden in derived classes. Interfaces cannot include implementations." -- this is something you need to consider.

    also read "Recommendations for Abstract Classes vs. Interfaceshttps://msdn.microsoft.com/en-us/library/scsyfw1d(v=vs.71).aspx 

    END EDIT.

    EDIT # 2:

    sbenhoff, regarding your code specifically -- before you show your code to your junior programmers, it would be a good idea to check whether LINQPad and/or Visual Studio is happy with your code.

        Amount = 1;   // Invalid token '=' in class, struct, or interface member declaration
        Int32 Amount = 1; // this compiles but is flawed

    sbenhoff, you need to test your code in an example before giving it to your junior programmers; you also need to think deeply about your example.

    public class DollarBill : PaperCurrency
    {
        Int32 Amount = 1;  
    public class Quarter : CoinCurrency
    {
        Int32 Amount = 25;   

    The above code indicates that one Quarter is worth 25 DollarBill -- also, you have this error for both classes:
    inconsistent accessibility: base class 'UserQuery.PaperCurrency' is less accessible than class 'UserQuery.DollarBill'
    inconsistent accessibility: base class 'UserQuery.CoinCurrency' is less accessible than class 'UserQuery.Quarter'
    [you will see "UserQuery" if you're testing with LINQPad]

    sbenhoff, your code has other issues ... for example, you may want to consider an enum for dollar, quarter, et cetera.

    you may also want to indicate to your junior programmers what culture is intended ... in Canada we have a CDN$2 coin and no longer use CDN 1 cent coins.

    sbenhoff, you will discover that creating appropriate training materials often takes much more thought than routine code.  FWIW

    END EDIT #2.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 14, 2015 12:04 PM
  • User-1078840699 posted

    Abstract classes and interfaces

    Like a non-abstract class, an abstract class must provide implementations of all members of the interfaces that are listed in the base class list of the class. However, an abstract class is permitted to map interface methods onto abstract methods. For example

    interface IMethods
    {
       void F();
       void G();
    }
    abstract class C: IMethods
    {
       public abstract void F();
       public abstract void G();
    }

    Here, the implementation of IMethods maps F and G onto abstract methods, which must be overridden in non-abstract classes that derive from C.

    Note that explicit interface member implementations cannot be abstract, but explicit interface member implementations are of course permitted to call abstract methods. For example

    interface IMethods
    {
       void F();
       void G();
    }
    abstract class C: IMethods
    {
       void IMethods.F() { FF(); }
       void IMethods.G() { GG(); }
       protected abstract void FF();
       protected abstract void GG();
    }

    Here, non-abstract classes that derive from C would be required to override FF and GG, thus providing the actual implementation of IMethods.

    Also, Do check this http://www.c-sharpcorner.com/UploadFile/93126e/difference-between-abstract-class-and-an-interface/ and this

    http://www.ronaldwidha.net/2008/06/16/a-good-example-of-abstract-class-vs-interface/

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 14, 2015 3:27 PM
  • User281315223 posted

    Abstract Classes and Interfaces

    Abstract classes will allow you to insert basic functionality and methods (implementation details) within your actual classes unlike Interfaces which will not (so abstract classes can ultimately reduce the amount of code that you may have to write).

    If you want a more detailed discussion, I would recommend checking out the following exhaustive Stack Overflow discussion on the topic : 

    There really is no always use one or always use the other and it is almost completely up to the preference of the developer and the needs that he or she needs to make (most of these decisions will come from future inheritance as both of these are heavily involved in being derived from).

    If you needed to implement functionality that a ton of your classes would share such as a specific property or method and the implementation would be the exact same for all of them, then you would want to use an abstract class. However, if you wanted each of the classes to have a method or property but allow each of them to provide their own implementation for it (similar to that of a blueprint) then an interface may be a better choice.

    I'd strongly encourage you to check out some of the links provided below, which discuss when to use one over another like these  : 

    As far as real world examples, anytime that you see an actual class that beings with an "I" typically denotes an interface. So things like IEnumerable, IQueryable and IConnection are all interfaces that have cooresponding implementations (Enumerable, Queryable, Connection). 

    A common example that you might read on several sites may sound as follows : 

    1. Are there many classes that can be "grouped together" and described by one noun? If so, have an abstract class by the name of this noun, and inherit the classes from it. (A key decider is that these classes share functionality, and you would never instantiate just an Animal... you would always instantiate a certain kind of Animal: an implementation of your Animal base class)
    Example: Cat and Dog can both inherit from abstract class Animal, and this abstract base class will implement a method void Breathe() which all animals will thus do in exactly the same fashion. (I might make this method virtual so that I can override it for certain animals, like Fish, which does not breath the same as most animals).

    2. What kinds of verbs can be applied to my class, that might in general also be applied to others? Create an interface for each of these verbs.
    Example: All animals can be fed, so I will create an interface called IFeedable and have Animal implement that. Only Dog and Horse are nice enough though to implement ILikeable - I will not implement this on the base class, since this does not apply to Cat.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 14, 2015 5:38 PM

All replies

  • User-434868552 posted

    @sbenhoff`   welcome to forums.asp.net

    you will like find this post useful:  http://forums.asp.net/post/5219333.aspx 

    also:

    For questions like "Difference between interface and abstract class", Google and/or your favourite search engine(s) is very helpful:

    http://lmgtfy.com/?q=Difference+between+interface+and+abstract+class 

    EDIT:

    How can I use interface and abstract class better?

    at http://forums.asp.net/post/4792310.aspx, Mike Brind wrote "Abstract classes can include implementations of methods which can be over-ridden in derived classes. Interfaces cannot include implementations." -- this is something you need to consider.

    also read "Recommendations for Abstract Classes vs. Interfaceshttps://msdn.microsoft.com/en-us/library/scsyfw1d(v=vs.71).aspx 

    END EDIT.

    EDIT # 2:

    sbenhoff, regarding your code specifically -- before you show your code to your junior programmers, it would be a good idea to check whether LINQPad and/or Visual Studio is happy with your code.

        Amount = 1;   // Invalid token '=' in class, struct, or interface member declaration
        Int32 Amount = 1; // this compiles but is flawed

    sbenhoff, you need to test your code in an example before giving it to your junior programmers; you also need to think deeply about your example.

    public class DollarBill : PaperCurrency
    {
        Int32 Amount = 1;  
    public class Quarter : CoinCurrency
    {
        Int32 Amount = 25;   

    The above code indicates that one Quarter is worth 25 DollarBill -- also, you have this error for both classes:
    inconsistent accessibility: base class 'UserQuery.PaperCurrency' is less accessible than class 'UserQuery.DollarBill'
    inconsistent accessibility: base class 'UserQuery.CoinCurrency' is less accessible than class 'UserQuery.Quarter'
    [you will see "UserQuery" if you're testing with LINQPad]

    sbenhoff, your code has other issues ... for example, you may want to consider an enum for dollar, quarter, et cetera.

    you may also want to indicate to your junior programmers what culture is intended ... in Canada we have a CDN$2 coin and no longer use CDN 1 cent coins.

    sbenhoff, you will discover that creating appropriate training materials often takes much more thought than routine code.  FWIW

    END EDIT #2.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 14, 2015 12:04 PM
  • User-1078840699 posted

    Abstract classes and interfaces

    Like a non-abstract class, an abstract class must provide implementations of all members of the interfaces that are listed in the base class list of the class. However, an abstract class is permitted to map interface methods onto abstract methods. For example

    interface IMethods
    {
       void F();
       void G();
    }
    abstract class C: IMethods
    {
       public abstract void F();
       public abstract void G();
    }

    Here, the implementation of IMethods maps F and G onto abstract methods, which must be overridden in non-abstract classes that derive from C.

    Note that explicit interface member implementations cannot be abstract, but explicit interface member implementations are of course permitted to call abstract methods. For example

    interface IMethods
    {
       void F();
       void G();
    }
    abstract class C: IMethods
    {
       void IMethods.F() { FF(); }
       void IMethods.G() { GG(); }
       protected abstract void FF();
       protected abstract void GG();
    }

    Here, non-abstract classes that derive from C would be required to override FF and GG, thus providing the actual implementation of IMethods.

    Also, Do check this http://www.c-sharpcorner.com/UploadFile/93126e/difference-between-abstract-class-and-an-interface/ and this

    http://www.ronaldwidha.net/2008/06/16/a-good-example-of-abstract-class-vs-interface/

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 14, 2015 3:27 PM
  • User281315223 posted

    Abstract Classes and Interfaces

    Abstract classes will allow you to insert basic functionality and methods (implementation details) within your actual classes unlike Interfaces which will not (so abstract classes can ultimately reduce the amount of code that you may have to write).

    If you want a more detailed discussion, I would recommend checking out the following exhaustive Stack Overflow discussion on the topic : 

    There really is no always use one or always use the other and it is almost completely up to the preference of the developer and the needs that he or she needs to make (most of these decisions will come from future inheritance as both of these are heavily involved in being derived from).

    If you needed to implement functionality that a ton of your classes would share such as a specific property or method and the implementation would be the exact same for all of them, then you would want to use an abstract class. However, if you wanted each of the classes to have a method or property but allow each of them to provide their own implementation for it (similar to that of a blueprint) then an interface may be a better choice.

    I'd strongly encourage you to check out some of the links provided below, which discuss when to use one over another like these  : 

    As far as real world examples, anytime that you see an actual class that beings with an "I" typically denotes an interface. So things like IEnumerable, IQueryable and IConnection are all interfaces that have cooresponding implementations (Enumerable, Queryable, Connection). 

    A common example that you might read on several sites may sound as follows : 

    1. Are there many classes that can be "grouped together" and described by one noun? If so, have an abstract class by the name of this noun, and inherit the classes from it. (A key decider is that these classes share functionality, and you would never instantiate just an Animal... you would always instantiate a certain kind of Animal: an implementation of your Animal base class)
    Example: Cat and Dog can both inherit from abstract class Animal, and this abstract base class will implement a method void Breathe() which all animals will thus do in exactly the same fashion. (I might make this method virtual so that I can override it for certain animals, like Fish, which does not breath the same as most animals).

    2. What kinds of verbs can be applied to my class, that might in general also be applied to others? Create an interface for each of these verbs.
    Example: All animals can be fed, so I will create an interface called IFeedable and have Animal implement that. Only Dog and Horse are nice enough though to implement ILikeable - I will not implement this on the base class, since this does not apply to Cat.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 14, 2015 5:38 PM
  • User-1601169661 posted

    check this one....Difference between Abstract Class and Interface

    William

    Saturday, May 30, 2015 2:03 AM