重写方法中是否可以有专门的参数?
假设我有一个名为“shape”的抽象父类,并且有多个子类(三角形、正方形、圆形...)。 我想在父“shape”类中定义一个所有子类都必须实现的抽象方法,我们称之为“draw”。 因此所有形状子类都必须提供“draw()”方法。 但是,draw 方法采用“Stencil”类型的参数,并且并非每个形状子类都可以使用任何模板...
因此存在一个抽象“shape”类、多个形状子类和多个模板。 我需要在形状类中定义一个绘制方法。 正方形可能使用 Stencil1,圆形可能使用 Stencil2。
我猜泛型可以解决这个问题,但我不确定。 每个形状子类都需要使用特定的模板来定义绘制方法,因为这些类也被其他类使用,并且编译器应该强制所有程序员使用该类支持的模板来调用绘制方法。 我们不能定义像“public abstract void draw(Stencil s)”这样的抽象方法,因为这样程序员可以将任何模板传递给 square 类,而 square 类只支持“Stencil1”
有什么想法吗?
更新1: 应该补充的是,形状类并不关心子类使用哪个模板,但由于子类也在其他类中使用,因此定义绘制方法非常重要,以便编译器只接受支持的模板。
Let's say I have an abstract parent class called "shape", and that there are multiple subclasses (triangle, square, circle... ). I want to define an abstract method in the parent "shape" class which all subclasses must implement, let's call it "draw". So all shape subclasses must provide the "draw()" method. But, the draw method takes a parameter of type "Stencil", and, not every shape subclass can use just any stencil...
So there is one abstract "shape" class, multiple shape subclasses, and multiple stencils. I need a draw method defined in the shape class. A square might use Stencil1 and the circle might use Stencil2.
I'm guessing that generics would do the trick, but I'm not sure. Each shape subclass needs to define the draw method with a specific stencil because these classes are used by other classes as well, and the compiler should force all programmers to call the draw methods with the stencil that is supported by that class. We can't define an abstract method like "public abstract void draw(Stencil s)" because then the programmer could pass in any stencil to the square class, whereas the square class only supports "Stencil1"
Any ideas?
Update1:
Should add that the shape class doesn't care which stencil is used by the subclass, but since the subclasses are used in other classes too, it's important that the draw method is defined so that only the supported stencil is accepted by the compiler.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为你应该重新考虑你最初的设计。
当然,您可以通过使用instanceof等来解决这个问题。但是,这将导致一个非常混乱的API(如果这就是您使用它的目的)。
I think you should probably reconsider your initial design.
Of course, you could get around this by using instanceof, etc. However, this will result in a very confusing API (if that's what you are using it for).
如果您希望在编译时捕获此问题,请考虑以下选项:
If you want this to be caught at compile time, the following options come to mind:
定义一个抽象 Stencil 并让子类构造函数决定使用哪个模板类。
Define an abstact Stencil and let the subclass constructor decide which stencil class to use.