1

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);
    }
}
Lufftre
  • 118
  • 1
  • 2
  • 8
  • 1
    Well, if the method accepts only Triangles why use AbstractShape? Use Triangle directly no? – Marco Acierno Mar 29 '14 at 16:03
  • Can you show some more code. Your question is confusing, specially because of that `tick()`. We don't understand whether that is supposed to be constructor or method. – Rohit Jain Mar 29 '14 at 16:04

2 Answers2

1

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

danny
  • 21
  • 1
0

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();
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350