I have a class named component that takes a shape Object as a parameter. The main class which creates an object of component doesn't know exactly which type of shape it's sending to it, all it knows is that it sends an Abstract Shape. My component however knows it will only get a triangle and therefor use its specific attributes.

My question, How can I convert the Abstract parameter to a specific subclass of it? Example:

public class TriangleHandler extends AbstractHandler{
    //More
    //Code
    //Here
    public tick(AbstractShape shape){
        shape.doTrinagleStuff();
    }
}

public class MainClass{
    private AbstractShape currentShape;
    private AbstractHandler currentHandler;
    //More
    //Code
    //Here
    public tick(){
        currentHandler.tick(currentShape);
    }
}
有帮助吗?

解决方案 2

Just cast it:

public class TriangleHandler extends AbstractHandler{
    public tick(AbstractShape shape){
        // Since we KNOW it's a triangle, we can cast it
        Triangle triangle = (Triangle)shape;
        triangle.doTrinagleStuff();
    }
}

其他提示

You can't without casting. You can only execute methods defined in the abstract class which is ok if you implement it in triangle class with its specific implementation. To be able to run a method that is not defined in abstract you will have to cast

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top