Q:

Trace the following program and answer the questions | static methods in java

0

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());
 }
}
  1. Write the output of the above program
  2. Detect the logical error in the above program and correct it
  3. What would be the output once the logical error is corrected.
  4. The instance variable numStudents is accessed through the class name in getNumStudents(). Why?
  5. Will the following statement produce an error if we place it in the main? Student s = new Student();         If the answer is yes, why?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Average = 50.0

Average = 23.333333333333332

need an explanation for this answer? contact us directly to get an explanation for this answer
need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (2)

<< A chikcken farmer receives from a supplier young c...