简体   繁体   中英

Instantiating abstract class object in inheriting class

I need to find a way to instantiate an object from the abstract base class called Cell, inside the inheriting class called Spreadsheet. Everywhere I look people say it can't be done, but I am required to do it for a part of my homework and it specifically says that we can not make the parent class non abstract.

Here is the exact quote from the homework:

Again, you need to come up with a design here that actually allows the spreadsheet to create cells and there were hints before about how to do this. You cannot make the publicly declared cell class non-abstract.

The only "hints" i can think of is that the parent class is public abstract, the inheriting class is just a public class, and they are both in the same DLL.

Anyone have any ideas?

edit: (for more info) The spreadsheet class is supposed to hold a 2d array of Cells. so in order to populate this 2d array, we need to make cell objects and put then in the corresponding indexes in the 2d spreadsheet array. The only problem is that we cant make any cells because the cell class is abstract. So, how can i make a cell and put it in the array?

It means you need to use Cell as a base class, and the inheriting class needs to have at least some of the implementation.

It seems like this particular homework assignment is a bit of what would be called a " hospital pass " in football terms - Spreadsheet should not inherit from Cell as you mention.

In any case once you've written your derived class you can do this:

Cell myCell = new MyDerivedCell();

and voila, you have an instance of an abstract class (abstract classes cannot be instantiated directly).

The advantage of this is that you can put the bulk of the generic cell functionality into Cell , then specify some methods or properties that should be overridden for the more specialised derivations of the Cell .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM