View this PageEdit this PageAttachments to this PageHistory of this PageHomeRecent ChangesSearch the SwikiHelp Guide

Failure to use object references with method calls

If you are calling an object method that isn't in the class your method is in then you must call it on an object of the right class. For example if you are in a ClassPeriod class that has a private array of students called studentArray and you want to
find and return the student who has the highest average:

public Student findHighestAverage()
{
  int highest = 0;
  int highestIndex = 0;
  for (int i = 0; i < studentArray.length(); i++)
  {
    if (getAverage() > highest)
    {
      highest = getAverage();
      highestIndex = i;
    }
  } 
  return studentArray[highestIndex];
}


You need to call the getAverage method on a student object.

public Student findHighestAverage()
{
  int highest = studentArray[0].getAverage();
  int highestIndex = 0;
  Student student = null;
  for (int i = 1; i < studentArray.length(); i++)
  {
    student = studentArray[i];
    if (student.getAverage() > highest)
    {
      highest = student.getAverage();
      highestIndex = i;
    }
  } 
  return studentArray[highestIndex];
}


Link to this Page