JAVA PROGRAM
Program to count and display total number of objects created to a class |Java Program|
Introduction
In Java, understanding how to keep track of the number of instances (objects) created from a class can be very useful, especially in scenarios where resource management and monitoring are crucial. In this blog post, we will explore a simple Java program that demonstrates how to count and display the total number of objects created for a class. Let’s dive into the code and break it down step by step.
Here's the Java program that counts and displays the total number of objects created for the Test class:
Code
import java.io.*;
import java.util.*;
class Test {
static int num = 0;
public Test() {
num += 1;
}
public static void main(String args[]) {
Test t1 = new Test();
Test t2 = new Test();
Test t3 = new Test();
System.out.println("Total number of objects = " + Test.num);
}
}
Output
Total no:of objects=3
In this example, the user inputs the number 5. The program then calculates and prints the factorial of 5, which is 120.
You can try running the program with different input numbers to observe how it accurately calculates the corresponding factorials. The output will display the factorial of the entered number using an iterative approach.
Explanation
1. The Test class is defined with a static variable num that keeps track of the number of objects created.
2. The static keyword ensures that num is shared among all instances of the Test class. This means that any change to num by one instance will be reflected across all instances.
3. The constructor of the Test class increments the num variable by 1 every time a new instance of Test is created. This is where the counting happens.
4. In the main method, three instances of the Test class are created (t1, t2, and t3). After creating these objects, the total number of objects created is printed out using System.out.println.
Conclusion
Counting the number of objects created from a class is a fundamental technique that can have numerous applications in real-world programming. This simple Java program demonstrates how to achieve this using a static variable and a constructor. By understanding and utilizing static variables, developers can effectively monitor and manage object creation in their applications.
Post a Comment
0 Comments