012-001-012
Static Variable Sharing and Independence
Hard
Problem Description
static variable Sharing and Independence
In this problem, you will create a program that implements a Counter class managing the total number of instances via a static variable while assigning a unique ID to each object, then displays the results to standard output.
Learning Objective: Understand how static variables are shared across all instances and differ from instance variables
Overview
Static variables are shared among all instances of a class. Instance variables hold independent values for each object.
Specifications
- Create a Counter class
- Use static variable totalCount to track total instance count
- Use instance variable id to track each object number
- constructor increments totalCount and assigns current totalCount to id
- Read integer n from standard input, create n instances and display each id and totalCount
Input Format
n
- Line 1: number of Counter instances to create n (1 ≤ n ≤ 10)
Output Format
Counter 1 created (total: 1)
Counter 2 created (total: 2)
...
Counter n created (total: n)
Final total: n
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up