Lets say I want to design a abstract system for counting sections in a document. I designed two classes, Document and Section, the document has a list of sections and a method to count them.
public abstract class Document {
List<Section> sections;
public void addSection(Section section) {
sections.Add(section);
}
public int sectionCount() {
return sections.count;
}
}
public abstract class Section {
public string Text;
}
Now, I want to be able to use this code in multipe scenarios. For example, I have Books with Chapters. The Book would be a subclass of Document, and Chapter a subclass of Section. Both classes will contain extra fields and functionality, unrelated to the counting of sections.
The problem I stumble upon now is that because Document contains sections, and not Chapters, the added functionality of Chapter is useless to me, it can only added as a section to Book.
I was reading about downcasting, but really think this is not the right way to go. I'm thinking maybe I took the wrong approach altogether.
My question comes to this: How do I design such an abstract system, that can be reused by subclassed objects, and is this the way to go?