题目:
仔细阅读DataSet.java,该类实现了如下功能:
- 通过add (…)接收一组double类型数据;
- 通过getAverage()返回接收到的所有数据的平均值;
- 通过getMaximum()返回接收到的所有数据中最大的一个;
利用接口技术改写此程序,扩展程序功能,要求改写后程序能够实现:
- 通过add(…)接收一些自定义的类的对象;(提示:这些类实现了某个接口,而这个接口中的某个方法返回了类的测量值);
- 通过getAverage()返回接收到的所有对象测量值的平均值;
- 通过getMaximum()返回接收到的所有对象测量值最大的一个对象;
并用改写后的DataSet类,接收一组Human/Student对象,输出这一组对象的平均值,和其中测量值最大的一个对象。
原DataSet.java:
/**
Computes the average of a set of data values.
*/
public class DataSet
{
/**
Constructs an empty data set.
*/
public DataSet()
{
sum = 0;
count = 0;
maximum = 0;
}
/**
Adds a data value to the data set
@param x a data value
*/
public void add(double x)
{
sum = sum + x;
if (count == 0 || maximum < x) maximum = x;
count++;
}
/**
Gets the average of the added data.
@return the average or 0 if no data has been added
*/
public double getAverage()
{
if (count == 0) return 0;
else return sum / count;
}
/**
Gets the largest of the added data.
@return the maximum or 0 if no data has been added
*/
public double getMaximum()
{
return maximum;
}
private double sum;
private double maximum;
private int count;
}
代码如下:
Inter接口:
package HW1102;
public interface Inter {
public double getData();
}
Human类:
package HW1102;
public class Human implements Inter {
private String name;
private int age;
public Human() {
}
public Human(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public double getData() {
return this.age;
}
}
DataSet类:
package HW1102;
/**
* Computes the average of a set of data values.
*/
public class DataSet {
/**
* Constructs an empty data set.
*/
public DataSet() {
sum = 0;
count = 0;
maximum = 0;
}
/**
* Adds a data value to the data set
*
* @param x a data value
*/
public void add(Human h) {
sum = sum + h.getData();
if (count == 0 || maximum < h.getData())
maximum = h.getData();
count++;
}
/**
* Gets the average of the added data.
*
* @return the average or 0 if no data has been added
*/
public double getAverage() {
if (count == 0)
return 0;
else
return sum / count;
}
/**
* Gets the largest of the added data.
*
* @return the maximum or 0 if no data has been added
*/
public double getMaximum() {
return maximum;
}
private double sum;
private double maximum;
private int count;
}
Student类:
package HW1102;
public class Student extends Human {
private int score;
public Student() {
}
public Student(String name, int age, int score) {
super(name, age);
this.score = score;
}
public int getGrade() {
return score;
}
}
Test:
package HW1102;
public class Test {
public static void main(String[] args) {
Human h1 = new Human("Tom", 18);
Human h2 = new Human("Jerry", 20);
Student s1 = new Student("Amy", 15, 90);
Student s2 = new Student("Bob", 13, 85);
DataSet ds = new DataSet();
ds.add(h1);
ds.add(h2);
ds.add(s1);
ds.add(s2);
System.out.println(ds.getAverage());
System.out.println(ds.getMaximum());
}
}