I am trying to find an example that includes both overridden methods and subclass-specific methods and I can't seem to find any. It seems like in the past I've used a base class to take advantage of
polymorphism, and have then wanted to use the derived instances. Is this something that never happens or should never happen? Here is an example:
List<Shape> shapes = new ArrayList<Shape>();
list.add(new Circle());
list.add(new Rectangle());
list.add(new Triangle());
for (Shape shape : shapes)
{
shape.printArea();
}
Ok, now I want to call specific (not overridden) methods in each of these derived classes (such as getRadius() in the Circle class). But in order to get the derived instances from the list, I would have to downcast and call instanceof (ugly, right?). So instead, I could do this:
Circle circle = new Circle();
Rectangle rectangle = new Rectangle();
Triangle triangle = new Triangle();
Now I can call the subclass-specific methods. But in this case, it would be fewer lines of code to just call printArea() for each instance instead of using the base class Shape.
So what is the best way to write this? Or should you never expect to have access to a subclass instance once you declare it using its superclass?