By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,984 Members | 1,016 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

abstract class

P: 1
An abstract method has no implementation. Its implementation logic is provided instead by classes that derive from it. We use an abstract class to create a base template for derived classes.

Expand|Select|Wrap|Line Numbers
  1. using System;
  3. abstract class Test
  4. {
  5.     public int _a;
  6.     public abstract void A();
  7. }
  9. class Example1 : Test
  10. {
  11.     public override void A()
  12.     {
  13.     Console.WriteLine("Example1.A");
  14.     base._a++;
  15.     }
  16. }
  18. class Example2 : Test
  19. {
  20.     public override void A()
  21.     {
  22.     Console.WriteLine("Example2.A");
  23.     base._a--;
  24.     }
  25. }
  27. class Program
  28. {
  29.     static void Main()
  30.     {
  31.     // Reference Example1 through Test type.
  32.     Test test1 = new Example1();
  33.     test1.A();
  35.     // Reference Example2 through Test type.
  36.     Test test2 = new Example2();
  37.     test2.A();
  38.     }
  39. }
Derived classes. When you create a derived class like Example1 or Example2, you must provide an override method for all abstract methods in the abstract class. The A() method in both derived classes satisfies this requirement.

Int field. An abstract class can have an instance field in it. The derived classes can access this field through the base syntax. This is a key difference between abstract classes and interfaces.

Cannot instantiate abstract class. The important part of an abstract class is that you can never use it separately from a derived class. Therefore in Main you cannot use the new Test() constructor.

However:You can use the Test type directly once you have assigned it to a derived type such as Example1 or Example2.
Aug 30 '14 #1
Share this Article
Share on Google+