this might be something very obvious but i am really struggling with the problem, any help would be appreciated.
i am trying to make a program that has an Activity class, which is a superclass for Run Swim Cycle classes, and there is another class called member.
a member has an arraylist called diary which keeps records of the distances made by a member
private ArrayList<Activity>diary = new ArrayList<>();
activities are added like so:
public void addActivity(Activity a){
diary.add(a);
}
now i need to get the distances for each of the classes in to an array and display the correct distance covered in each type of activity, i tried doing this:
public double[] getTotalDistances(){
double distance[];
distance = new double[3];
for (Activity r: diary){
distance[0] += r.getDistance();
}
for(Activity c: diary ){
distance[1] += c.getDistance();
}
for(Activity s: diary ){
distance[2] += s.getDistance();
}
for(int i = 0; i < distance.length; i++){
System.out.println(distance[i]);
}
return distance;
}
but this returns the getDistance() method of only the superclass, if i do this:
for (Run r: diary){
distance[0] += r.getDistance();
}
then java complains that those are incompatible types :
incompatible types. required: run, found: activity.
if run is a subclass of activity then why would it complain about incompatibility? and how do i get it to work with the correct method (the getDistance method that is in the "run" class)
THanks!
diarycontain objects of typeActivity, notRun.getDistanceof whatever the object is actually an instance of. The type of the reference doesn't matter.