Posted By


BrentS on 07/29/11

Tagged


Statistics


Viewed 642 times
Favorited by 0 user(s)

AbstractClassExample


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /*
  2.  * An abstract class can contain some common functionality, such as the
  3.  * "YouDontHaveToWriteThisFunctionAgain" method. This function can be called
  4.  * from the class that inherits this AbstractTest class using the base keyword:
  5.  * base.YouDontHaveToWriteThisFunctionAgain()
  6.  * Also the class that inherits this AbstractTest class must implement the other
  7.  * functions marked "abstract". That is, the inheriting class must define its
  8.  * own function for those abstract members.
  9.  */
  10.  
  11. public abstract class AbstractTestBase
  12. {
  13. private const int m_multiplier = 2;
  14.  
  15. // The class inheriting AbstractTestBase can call this function by using
  16. // the base keyword: base.YouDontHaveToWriteThisFunctionAgain()
  17. // If you don't intend to have a common, reusable function like this, then
  18. // you shouldn't use an abstract class. Instead, create an interface class.
  19. // NOTE: Use the "public" access modifier instead of "protected" if you want
  20. // to allow the implimenting class to have direct access to this function.
  21. protected int YouDontHaveToWriteThisFunctionAgain(int value)
  22. {
  23. return value * m_multiplier;
  24. }
  25.  
  26. // The class inheriting this must implement the following function.
  27. // We don't care how it is implemented, just that it is implemented.
  28. public abstract void YouMustImplementThis();
  29. }
  30.  
  31.  
  32.  
  33. // Now you can inherit from the AbstractTestBase class and use it like this:
  34. public class TestAbstractClass : AbstractTestBase
  35. {
  36.  
  37. // The key feature of an abstract class is that you can re-use code from the base:
  38. public int WrapAndUseAnAbstractMethod(int value)
  39. {
  40. return base.YouDontHaveToWriteThisFunctionAgain(value);
  41. }
  42.  
  43. public override void YouMustImplementThis()
  44. {
  45. // Add your code here for this function!
  46. throw new NotImplementedException("You have to write code here");
  47. }
  48. }
  49.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.