012-001-008

static Modifier: Shared Class Variables

Medium

Problem Description

static Modifier: Shared class Variables

In this problem, you will create a program that creates a Counter class with a static field count, reads the number of instances to create from Scanner input, instantiates that many Counters, and displays the total instance count to standard output.

Learning Objective: Understand how to use static fields to share data across all instances

Overview

Create a Counter class and use a static variable to count how many instances have been created. Verify that all instances share the same counter.

Specifications

  • Counter class static field: count (int type)
  • constructor: Increments count when instance is created
  • Static method getCount(): Returns current count value
  • In main method, read integer n via Scanner.nextInt(), create n instances in a loop, and output the count value

Input Format

n

n: number of instances to create (integer)

Output Format

Total instances: 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