Trace the following program and answer the questions
class Student {
private double sum;
private static int numStudents = 0;
public Student(double sum) {
numStudents++;
this.sum += sum;
}
public static int getNumStudents () {
return Student.numStudents;
}
public double getAverage() {
return sum / numStudents;
}
}
public class StudentDemo {
public static void main(String[] args) {
Student s1 = new Student(50);
System.out.println("Average = " + s1.getAverage());
new Student(60);
Student s3 = new Student(70);
System.out.println("Average = " + s3.getAverage());
}
}
- Write the output of the above program
- Detect the logical error in the above program and correct it
- What would be the output once the logical error is corrected.
- The instance variable numStudents is accessed through the class name in getNumStudents(). Why?
- Will the following statement produce an error if we place it in the main? Student s = new Student(); If the answer is yes, why?
1.
Average = 50.0
Average = 23.333333333333332
2.
private double sum should be : private static sum=0;
3.
4. because numStudents is a static variable.