Frage

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);
    }
}
War es hilfreich?

Lösung 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();
    }
}

Andere Tipps

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top