Beginner question about inheritance

I'm writing a program to help myself practice syntax. If I have a class "problem" from which each type of syntax problem inherits, which kinds of methods go in the parent vs the children? For instance, all of them have a method to generate a correct answer, but for each inherited class it is different. Should they inherit a generic method from the parent and overwrite it (and if so, what would the parent method contain?) or should they all just have their own method even if it has the same name and not have one in the parent?

Posted Aug 4, 2015, 5:25 AM UTC

18
[deleted]•

The parent contains anything the derived classes will have in common with each other. You then override the methods that need to behave differently in the derived class.

1
MAGllKARPOP•

Thank you so much! I'm getting back into programming for the first time in years so I'm rusty

1
MAGllKARPOP•

If the parent is a class that shouldn't ever have a reason to be instantiated, should I define its methods or just the parameters and leave the body blank?

1
simplyevert•

Which language are you working in? Sounds to me like Parent could be an abstract class

2
MAGllKARPOP•

I learned in C++ a few years ago (two years of programming at university) and now I'm using C#

1
simplyevert•

From MSDN

abstract class WashingMachine
{
   public WashingMachine()
   {
      // Code to initialize the class goes here.
   }

   abstract public void Wash();
   abstract public void Rinse(int loadSize);
   abstract public long Spin(int speed);
}

"In the above example, an abstract class is declared with one implemented method and three unimplemented methods. A class inheriting from this class would have to implement the Wash, Rinse, and Spin methods"

By doing something like this you can choose which functions to implement in the base class and which functions you just want to declare and then leave up to the inherited classes to implement. Note that you can't create an instance of an abstract class.

1