Reputation:
Over here i'm trying to make use of an interface called "Measurable" with one method called getMeasure. The problem is, I'm trying to get the average height of all the people in my program, by accessing the method in my interface. One of the problems I can't access the getMeasure method for some reason, and at last get the average height of all the people in the array. How can I solve this problem?
class Main {
public static void main(String args[]) {
Person[] people = new Person[4];
people[0] = new Person("Larry", 65);
people[1] = new Person("Susan", 45);
people[2] = new Person("Joe", -45);
people[3] = new Person("", 0);
double averageHeight = average(people);
}
public static double average(Person[] objects)
{
if (objects.length == 0) { return 0; }
double sum = 0;
for (Person obj : objects)
{
double measure = obj.getMeasure();
sum = sum + measure;
}
double result = sum / objects.length;
return result;
}
}
interface Measurable {
double getMeasure();
}
public class Person {
private String name;
private Integer height;
public Person(String name, Integer height)
{
this.name = name;
this.height = height;
}
public double getMeasure() {
return height;
}
}
Upvotes: 2
Views: 640
Reputation: 1405
The Person
class should implement Measurable
:
public class Person implements Measurable {
...
}
Then if you want to make your average
function reusable (I guess this is your desired outcome), you should replace the Person
instance with Measurable
:
public static double average(Measurable[] objects) {
...
for (Measurable obj : objects){
...
}
}
This way you could have different Measurable
implementations to calculate the average.
Upvotes: 4
Reputation: 1
public class Person implements Measurable {
private String name;
private Integer height;
public Person(String name, Integer height)
{
this.name = name;
this.height = height;
}
@Override
public double getMeasure() {
return height;
}
You have to implement the to use it. If the Interface also implements the method, you have to add the @Override modifier.
Upvotes: 0