This is a problem I've been working on for a little while now and I've barely made any progress. I've been running into a lot of problems trying to use an abstract class when extending ArrayList.
My first step was to define three classes, Circle, Rectangle, and Triangle that are all concrete subclasses of an abstract class GeometricObject. The base class has abstract methods getArea() and getPerimeter() that are overridden in the subclasses by the specific getPerimeter() and getArea() formula for that particular object. This part is completed and is working as intended.
The next part is where I'm having trouble. I'm supposed to define a new class GeoemetricObjectList that extends ArrayList<GeometricObject>. This class should override the add(), remove(), and clear() methods. This class keeps a totalArea and totalPerimeter variable of the objects on the list.
Right now I've created a, quite frankly, messy if statement list in my GeometricObjectList add() method that I'd like to clean up. Here is my code for that class so far:
import java.util.ArrayList;
@SuppressWarnings("hiding")
public class GeometricObjectList<GeometricObject> extends ArrayList<GeometricObject>{
final static long serialVersionUID = 1L;
public double totalArea = 0;
public double totalPerimeter = 0;
public boolean add(GeometricObject element){
if(element instanceof Rectangle) {
totalArea += ((Rectangle)element).getArea();
totalPerimeter += ((Rectangle)element).getPerimeter();
}
if(element instanceof Circle) {
totalArea += ((Circle)element).getArea();
totalPerimeter += ((Circle)element).getArea();
}
if(element instanceof Triangle) {
totalArea += ((Triangle)element).getArea();
totalPerimeter +=((Triangle)element).getArea();
}
return super.add(element);
}
public boolean remove(GoemetricObject element) {
return super.remove(element);
}
public void clear() {
}
}
When I simply write totalArea += element.getArea() I get the error "The method getArea() is undefined for the type GeometricObject but in my GeometricObject class I have a public abstract getArea() that is overridden by the getArea() method in each concrete (Triangle, Circle, Rectangle) class.
My next issue is with the remove() method in GeometricObjectList. It looks like this:
public boolean remove(GeometricObject element) {
return super.remove(element);
}
I am getting the error "Name clash: The method remove(GeometricObject) of type GeometricObjectList<GeometricObject> has the same erasure as remove(Object) of type ArrayList but does not override it". I never received this error when creating the add() method.
Any help with this is REALLY greatly appreciated. If there's any more info you need ask for it and I'll have it up in a second!
public class GeometricObjectList<GeometricObject>is declaring a type parameter named GeometricObject. I assume you meantpublic class GeometricObjectList extends ArrayList<GeometricObject>.