Java Program to Count Number of Objects Created

Java program to create number of objects created. Create a student class with properties roll no, name, percentage. Define a default and parameterized constructor. Keep count of objects created. Display the information of students. (Hint: use static member and method).

Java Program to Count Number of Objects Created

Here is the source code of java program to count the number of objects created.
import java.io.*;

class Student {

 int rollno;
 String name;
 double perc;
 static int objCreated = 0;
 

 Student()
 {
  rollno = 0;
  name = null;
  perc = 0.0;
  objCreated++;
 }

 Student(int r,String n, double p)
 {
  rollno = r;
  name = n;
  perc = p;
  objCreated++;
 }

 static void displayCount()
 {
  System.out.println("Number of objects created: " + objCreated+"\n");
 }

 void display()
 {
  System.out.println("*** Student Information ***");
  System.out.println("Roll No: " + rollno);
  System.out.println("Name: " + name);
  System.out.println("Percentage: " + perc);
  System.out.println("\n");
 }
}

public class CountNumberofObjects{

 public static void main(String args[])
 {
  Student s1 = new Student(102,"Amar",80.99);

  s1.displayCount();
  s1.display();

  Student s2 = new Student(103,"Chinmay",80.99);

  s2.displayCount();
  s2.display();
 }

}

Output:

/* Output of above code:

Number of objects created: 1

*** Student Information ***
Roll No: 102
Name: Amar
Percentage: 80.99


Number of objects created: 2

*** Student Information ***
Roll No: 103
Name: Chinmay
Percentage: 80.99

*/

Comments