سؤال

I am new to C# programming. I understand that it is necessary to modify the class as abstract if it contains any abstract methods, and its implementation must be provided in any of the child classes in class hierarchy.
But my question is whether can we have an abstract class without any abstract methods(so it is not necessary for it to be a base class), and if it is so, then what are the significance of the same. Please help in this regard. :)

هل كانت مفيدة؟

المحلول

Yes you can have an abstract base class without any abstract methods. The benefit is that you cannot create an instance of this class.

There is a consideration to replace that abstract class with an interface. The difference is that the interface may not contain any implementation, but in the abstract class you can provide some implementation for methods that any inheritor may use.

نصائح أخرى

You cann't create instances of the abstract class, and if you are not use this class as base - it is useless (only possible for some tricky goals using reflection)

Yes, it can be used without having an implementing subclass. Basically you have three "ways" of defining and calling methods here:

  • static: Methods that can be called directly on the abstract class, because they do not require an instance at all.
  • abstract: Methods that must be implemented in a sub-class (note that the existance of one of these does not stop you from using any existing static methods directly!)
  • "Regular": Normal methods, implemented directly in the abstract class, and which can be called via an instance of a sub-class. Note that you can only call them via sub-classes, since you can only have instances of a subclass (not the abstract class itself). Such a sub-class must also by definition implement any abstract method(s) in the abstract class (otherwise you`ll get a compile time error).

The following simple console app gives a nice, concrete (no pun intended) example:

using System;
namespace ConsoleStuff
{
    public abstract class MyAbstractClass
    {
        public abstract void DoSomethingAbs();

        public void DoSomethingElse()
        {
            Console.WriteLine("Do something general...");
        }

        public static void TakeABreak()
        {
            Console.WriteLine("Take a break");
        }
    }

    class MyImplementation : MyAbstractClass
    {
        public override void DoSomethingAbs()
        {
            Console.WriteLine("Do something Specific...");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Static method; no instance required
            MyAbstractClass.TakeABreak();

            var inst = new MyImplementation();
            inst.DoSomethingAbs();  // Required implementation in subclass
            inst.DoSomethingElse(); // Use method from the Abstract directly

            Console.ReadKey();
        }
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top