A program combining a switch statement with static variables in a class. Based on the switch statement, a class object is dynamically created.
SwitchBlocks
package switchblocks;
public class SwitchBlocks
{
public static void main(String args[])
{
int input = 100;
do
{
System.out.print("\n\tEnter a positive integer (0 to stop)");
input = MyInput.readInt();
switch (input)
{
case 1: A myA = new A(); break;
case 2: B myB = new B(); break;
default: System.out.print("\n\tNo new objects created");
}
} while (input > 0);
System.out.print("\n\n\tNumber of A objects created = " + A.getA());
System.out.print("\n\n\tNumber of B objects created = " + B.getB());
}
}
class A
{
private static int nobjects = 0;
public A() { nobjects++; }
public static int getA() { return nobjects; }
}
class B
{
private static int nobjects = 0;
public B() { nobjects++; }
public static int getB() { return nobjects; }
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.