Help with Counting Objects Created in a Java Class

  • Context: Comp Sci 
  • Thread starter Thread starter lypaza
  • Start date Start date
  • Tags Tags
    Classes Java
Click For Summary

Discussion Overview

The discussion revolves around how to count the number of objects created in a Java class, specifically focusing on a class named Student. Participants explore various methods to implement this counting mechanism, including the use of static variables and constructors. The conversation includes technical explanations, code snippets, and questions regarding implementation details.

Discussion Character

  • Technical explanation
  • Exploratory
  • Homework-related

Main Points Raised

  • One participant expresses uncertainty about how to count objects created in a Java class and provides an initial method outline.
  • Another participant suggests using a static variable that increments each time an instance is created.
  • A question is raised about how to signal when an object is created, leading to a clarification that the constructor is called upon object creation.
  • Participants discuss the implementation of a constructor to increment a counter for created objects.
  • One participant proposes a method to count objects but questions its correctness, indicating confusion about the logic.
  • Another participant corrects the logic, emphasizing that the counter should be incremented within the constructor.
  • A participant shares their implementation of the Student class and asks for feedback on their code, particularly regarding the handling of course grades.
  • Discussion includes a question about the visibility and scope of a count variable when managing an array of Student objects.
  • A suggestion is made to encapsulate the count and array within a separate Students class for better management.
  • One participant mentions the potential use of a Vector for dynamic management of Student objects.

Areas of Agreement / Disagreement

Participants generally agree on the need to use a constructor to manage the counting of objects, but there are varying opinions on the best way to implement this, particularly regarding the management of the count variable and the structure of the code.

Contextual Notes

Some participants express uncertainty about specific implementation details, such as the proper handling of course grades and the visibility of the count variable in relation to the Student array.

lypaza
Messages
17
Reaction score
0
I have only 1 day to work on my lab. Hope someone could help me as soon as possible.

My problem is I don't know how to count how many objects are created in a class.

The first assignment is write a Java class, Student, that has the following instance variables: name (String), age (int), gpa (double), courseGrades (array of char: A, B, C, D, F)

The class also has methods that would calculate the GPA of the student.
Then test the program by creating some objects: Student s1 = new Student(); ... blah...blah

And the second assignment, today my instructor just added it, is count how many objects are created in the class.I just do a little like this :rolleyes:

Code:
public int getCount(){
        int count = 0;
        ...
        return count;
}

I don't know I could count it due to what things :frown:
 
Physics news on Phys.org
From what I remember of Java you would want to create a static variable that gets incremented each time an instance of your object is created.
 
Oh yeah, today we were talking about static variables.
But what signal would be to indicate the object is created? :confused:
 
When an object is created, the class's constructor is called.

- Warren
 
I still don't get it. Can you give me some more clue?
 
The Student class has a method, also called Student, which is referred to as a constructor:

PHP:
publc class Student {
  public Student(...) {
    ...
  }
}

(If no constructor exists explicitly, an empty constructor is assumed).

Every time you execute a line of code that involves "new Student(...)", the constructor is called. The constructor can keep track of how many Student objects have been created by incrementing a counter (stored a class variable) each time it is run.

- Warren
 
PHP:
public class Student{
       private static int count = 0;

       public int getCount(Student s){
              if (s == new Student())
              count++;
       }
}

I don't think it would be correct :rolleyes:
I feel I still miss something, do I need a loop to go through the class to get all of objected that are created? :confused: So complex
 
No, that won't work. The expression s == new Student() will always evaluate to false.

You need to put your counter code in the CONSRUCTOR. Like this:

PHP:
public class Student {
    private static int count = 0;

    public Student() {
        count = count + 1;
    }

    public int getCount() {
        return count;
    }
}

- Warren
 
Oh, my! I couldn't think in that way.

If I don't have a default constructor methods, can I conbine like this?
PHP:
public class Student{
	private String name;
	private int age;
	private double gpa;
	private char [] courseGrade;
	private static int count = 0;

	public Student(String name, int age){
		this.name = name;
		this.age = age;
		gpa = 0;
		courseGrade = null;
                count++;
	}
 
        public int getCount(){
                return count;
        }
        ......
}


By the way, would you mind to look over my program?

PHP:
public class Student{
	private String name;
	private int age;
	private double gpa;
	private char [] courseGrade;
	private static int count = 0;

	public Student(String name, int age){
		this.name = name;
		this.age = age;
		gpa = 0;
		courseGrade = null;
	}

	public String getName(){
		return name;
	}

	public int getAge(){
		return age;
	}

	public double getGpa(){
		return gpa;
	}

        public int getCount(){
                return count;
        }

	public void setGrades(char [] grades){
		courseGrade = new char [grades.length];
		for (int i = 0; i < grades.length; i++){     // Problem seems here, I don't know how to create the courseGrades from null. Is that ok?
			courseGrade[i] = grades [i];
		}

		for (int i = 0; i < grades.length; i++){
			switch (grades[i]){
				case 'A': gpa += 4;
				break;
				case 'B': gpa += 3;
				break;
				case 'C': gpa += 2;
				break;
				case 'D': gpa += 1;
				break;
			}
			gpa /= grades.length;
		}
	}

	public String toString () {
		String tempString = "";
		tempString.format("Name: %s \n Age: %d \n GPA: %4.2f \n Grades: ",
		                                                  name, age, gpa);
		for (int i = 0; i < courseGrade.length; i++) {
			tempString += courseGrade [i] + ", ";
		}

		return tempString;
	}

	public static void main (String[]args){
		Student s1 = new Student ("Joe", 19);
		char grades1 [] = {'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B'};

		s1.setGrades(grades1);
		s1.getGpa();
		s1.toString();

		Student s2 = new Student("Mary", 20);
		char grades2 [] = {'A', 'A' , 'B', 'B', 'C', 'C', 'D', 'D', 'F', 'F'};
		s2.getGpa();
		System.out.println("Before calculating the GPA \n" + s2.toString());
		s2.setGrades(grades2);
		s2.getGpa();
		System.out.println("After calculating the GPA \n" + s2.toString());
	}
}
 
  • #10
Yes, you've added "count++" to your constructor appropriately.

- Warren
 
  • #11
I have one more question about static variable.
If I have an array:
PHP:
Student [] students = new Student [20];
and I have to write a method to create a Student object and put a reference to this student in the students array.

For each time adding one student, I have to know how many students have added in the students array, so I think I need one more variable
PHP:
int count;
to do this.

I think this variable would be static, right?
 
  • #12
count probably should have the same visibility as your Student[] array. For example if your students array is a global static variable, that's what the count should be. If the students array is local and you pass it to the add student method, then you should also pass count to the add student method and have it return the new count. A good solution is to have a Students class that contains both the count and the students array, as well as the add student method. That way you do not have to keep track of count and students separately.

A better way would be to use a Vector<Student> (from package java.util.*). That will automatically report how many students are in it by the size() method and there is no limit on the number of students it can contain.
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 2 ·
Replies
2
Views
7K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 14 ·
Replies
14
Views
5K
  • · Replies 2 ·
Replies
2
Views
4K