简体   繁体   English

在继承类中实例化抽象类对象

[英]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. 我需要找到一种方法,可以在名为Spreadsheet的继承类中从名为Cell的抽象基类实例化对象。 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. 我能想到的唯一“提示”是父类是公共抽象,继承类只是公共类,并且它们都在同一个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. 因此,为了填充此2d数组,我们需要制作单元格对象,然后将其放入2d电子表格数组的相应索引中。 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. 这意味着您需要将Cell用作基类,并且继承类至少需要一些实现。

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. 看来,这项特殊的作业是足球术语中所谓的“ 医院通行证 ”的一部分- Spreadsheet不应像您提到的那样继承自Cell

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 . 这样做的好处是,您可以将大部分通用单元功能放入Cell ,然后指定一些方法或属性,这些方法或属性应针对Cell的更专业派生而被覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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