6.8. Abstract classes

The idea of abstract classes in C# is pretty much identical to that in Java – a class which cannot be instantiated, and which may contain abstract methods.

There follows an example of an abstract class, MyAbstractClass, which contains one abstract method, DoSomething(). MyClass inherits from MyAbstractClass and provides an implementation of the method. [14]

[14] On line 8, the override modifier is used to declare that DoSomething() is overriding the abstract method of the same name in the superclass.

 1: using System;
 2:
 3: public abstract class MyAbstractClass{
 4:   public abstract int DoSomething();
 5: }
 6:
 7: public class MyClass:MyAbstractClass{
 8:   public override int DoSomething(){
 9:     return 0;
10:   }
11:
12:   public static void Main(){
13:     MyClass mc = new MyClass();
14:     Console.WriteLine(mc.DoSomething());
15:   }
16: }

Like Java

  • An abstract class is one which cannot be instantiated. The only reason for the existence of an abstract class is for it to be subclassed.

  • An abstract class may contain zero or any number of abstract members. On the other hand, a class with at least one abstract member must be declared as an abstract class.

  • Subclasses of an abstract class must implement all abstract members (if any), or they will have to be declared as abstract themselves.

  • Abstract classes cannot be sealed. [15]

    [15] A sealed class is similar to a final class in Java (see section 6.7).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.151.220