19.4k views
2 votes
write a calss called animak that contains a static variable called count to keep track of the number of animals created

User TimT
by
6.2k points

1 Answer

0 votes

Answer:

Follows are the code to this question:

class Animal //defining a class Animal

{

static int count = 0;//defining static integer variable count

int myCount;//defining integer variable myCount

Animal() //defining default constructor Animal

{

myCount = ++count;//use myCount to hold incrementing value of count

}

public static int getCount()//defining a static method getCount

{

return count;//return count value

}

public static void setCount(int count)//defining a static method setCount that accept a parameter

{

Animal.count = count;//use class to hold value in count variable

}

public int getMyCount() //defining a method getMyCount

{

return myCount;//return myCount value

}

}

public class Main//defining a class Main

{

public static void main(String[] ax)//defining main method

{

Animal a1 = new Animal();//creating animal class object

Animal a2 = new Animal();//creating animal class object

Animal a3 = new Animal();//creating animal class object

System.out.println("Number of created animals: " + Animal.getCount());//calling static method

System.out.println("Number of created animals: " + Animal.getCount());//calling static method

System.out.println("Number of created animals: " + Animal.getCount());//calling static method

System.out.println("first animal count: " + a1.getMyCount());//calling getMyCount method

System.out.println("second animal count: " + a2.getMyCount());//calling getMyCount method

System.out.println("third animal count: " + a3.getMyCount());//calling getMyCount method

}

}

Output:

please find the attached file.

Step-by-step explanation:

please find the complete question in the attached file.

In the above-given code, a class "Animal" is defined, inside the class two integer variable "count and myCount" is defined, in which "count" is the static variable.

In the next step, the class constructor is defined that holds the incrementing value of count in the myCount variable, and use the get and set method to hold the value, in which set is static type.

In the main class, the "Animal" class object is created, which calls the getMyCount method to print its value and use the class name to call the set method.

write a calss called animak that contains a static variable called count to keep track-example-1
write a calss called animak that contains a static variable called count to keep track-example-2
User Tirso
by
6.5k points