Jen Francis

Greenhorn
+ Follow
since Jan 12, 2011
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Jen Francis

Stefaan Dutry wrote:

You could do the following at the declaration:



Or I could write:


In this case I am not taking advantage of polymorphism at all, although the printArea() method is part of the Shape class. This reduces the amount of code I would need to write by a few lines. I guess in this case it's a matter of whether you wanted to print all areas as a group (as in your example) or not. I guess I don't see what is so useful about polymorphism if you need to access subclass-specific methods as well as superclass methods (which is often going to be the case).
13 years ago
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?
13 years ago