Reputation: 4492
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.
Upvotes: 3
Views: 862
Reputation: 16868
Define an abstact Stencil and let the subclass constructor decide which stencil class to use.
private Stencil s;
public void draw(){
privateDraw(s)
}
private abstract void privateDraw(Stencil s);
Upvotes: 0
Reputation: 2118
public abstract class Shape<S extends Stencil>
{
public abstract void draw( S stencil );
}
public class Square extends Shape<Stencil1>
{
public void draw( Stencil1 stencil )
{
stencil.letsdo();
stencil.some();
stencil.drawing();
}
}
public class Circle extends Shape<Stencil2>
{
public void draw( Stencil2 stencil )
{
stencil.some();
stencil.more();
stencil.drawing();
}
}
Upvotes: 7
Reputation: 12080
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).
Upvotes: 1
Reputation: 41381
If you want this to be caught at compile time, the following options come to mind:
Upvotes: 0