Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: abstract and non-abstract methods in an abstract class?

I am not sure whether the code I'm writing makes sense. Here's the general idea:

I have a Parser class that will take different types of documents. Depending on the type, I will parse the document differently.

So suppose I have two types of documents, A and B. The factory pattern seems like a pretty good way to go about doing this in case I need to extend the program to handle additional types, so I will have an abstract class.

abstract class Parser
{
   ...
   public void common_method() {
      // something common that all parsers will use
      // like file IO
   }

   // derived classes will override this
   public abstract void specific_method();
}

class A_Parser : Parser
{
   ...
}

class B_Parser : Parser
{
   ...
}

The issue I'm wondering about is the fact that I have declared abstract methods and non-abstract methods in my abstract Parser. Compiler doesn't seem to be complaining, and it still seems to work correctly.

Is this non-standard? Maybe there's a better way to design this?

like image 342
MxLDevs Avatar asked Dec 04 '22 16:12

MxLDevs


2 Answers

This is perfectly fine. If you only had abstract methods, you'd have essentially an interface. You may have to use another pattern to create the actual instances of the parser if necessary, but as far as the class definition goes, this is pretty standard.

like image 196
carlosfigueira Avatar answered Dec 09 '22 14:12

carlosfigueira


This is very fine and you can even make some virtual methods that are not mandatory to override

like image 34
Alex Rose Avatar answered Dec 09 '22 13:12

Alex Rose