Reference leaks through a constructor and a getter

A Java class stores test scores in a private array:


Java
public class Gradebook {
    private int[] scores;

    public Gradebook(int[] scores) {
        this.scores = scores;
    }

    public int[] getScores() {
        return scores;
    }

    public double average() {
        int sum = 0;
        for (int s : scores) {
            sum += s;
        }
        return (double) sum / scores.length;
    }
}


Version A is the class exactly as shown. In Version B, the constructor uses this.scores = scores.clone(); and the getter uses return scores.clone();. In Version C, the constructor is as shown but the getter uses return scores.clone();. The same client code runs against each version:


Java
int[] data = {70, 80, 90};
Gradebook g = new Gradebook(data);
data[1] = 50;
int[] view = g.getScores();
view[2] = 60;
System.out.println(g.average());


Give the value printed by g.average() for each version, to one decimal place.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Encapsulation and Information Hiding Questions: