Please answer the following questions. 1. How can you count the number of instan
ID: 3555641 • Letter: P
Question
Please answer the following questions.
1. How can you count the number of instances(Objects) created for a certain class? Please explain in details using Java code lines, and in which parts of the class would you add these lines of code to be able to accomplish that.
2. Write a method that uses HashMaps and takes two parameters one of Type String that represents a student ID , and another of type Student, the hashmap should first check if there is an entry for that student in the Hashmap (based on the ID) and if not create an entry to the hashmap associating Students objects with student ID, otherwise the method should Print Out an error indicating that the student already exists in the Hashmap.
3. Write a method in JAVA that uses a switch statement and takes a person's age using an integer parameter , then checks if the age is valid (0-130), and then RETURNS a string based on the age using the following rules:
0-10 Child
11-19 Teenager
20-64 Adult
65- Senior
4. Criticize the first version of "world of Zul" example from Chapter 6, in terms of Design, using and showing that you understand the following terms (responsibility Driven design, cohesion , coupling, refactoring).
Explanation / Answer
1:-
you can count number of objects created using a static variable because static variable gets memory only once in class area at the time of class loading. you can add a static variable in constructor so everytime an object is created it increases its count
/* Program to Count Total Number of Objects Created for Class */
import java.io.*;
class abc
{
static int count;
abc()
{
count++;
System.out.println("objects"+count);
}
}
class mn
{
public static void main(String s[])
{
abc a1 = new abc();
abc a2 = new abc();
}
}