Java Program to count , how many times a method is called using different object.
Objective
Write a Java program to count how many times a method is called across multiple object instances.
Algorithm / Approach
- Create a class
Counter. - Declare a static integer variable
count = 0. - Define a method
counter()that incrementscount. - Define a method
display()that prints the value ofcount. - In
main, create aCounterobject and callcounter()twice. - Create a second
Counterobject and callcounter()twice again. - Call
display()to print the final count.
Counter.java
class Counter {
static int count = 0;
void counter(){
count++;
}
void display() {
System.out.println("Total time- "+count);
}
public static void main(String[] a)
{
Counter c = new Counter();
c.counter();
c.counter();
Counter c2 = new Counter();
c2.counter();
c2.counter();
c2.display();
}
}
Expected Output
Total time-4
Explanation of the Program
- This is a practical application of the static keyword. Since we want to track the total number of method calls across the entire program regardless of which object made the call, we must use a static variable.
- If
countwere not static, the first object would count to 2, and the second object would separately count to 2. By making it static, the count continues seamlessly from 2 up to 4.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)