package com.codegym.task.task04.task0407;
/*
Cats in the Universe
*/
public class Solution {
public static void main(String[] args) {
Cat cat1 = new Cat();
Cat.count = cat1.count;
//write your code here
Cat cat2 = new Cat();
Cat.count = cat2.count;
System.out.println("The cat count is " + Cat.count);
}
public static class Cat {
public static int count = 0;
public Cat() {
count++;
}
}
}
I got correct answer.But my question is how does it works especially Cat constructor
how does the programme works
Under discussion
Comments (1)
- Popular
- New
- Old
You must be signed in to leave a comment
Andrew
4 April 2019, 14:07useful
TL;DR: because the variable is static and public.
Explanation:
<public static class Cat> is an inner class inside the Solution Class.
Each time a new instance of Cat is declared <Cat cat1 = new Cat();> the Cat constructor is called.
The Cat constructor has no parameters but does increment the variable <public static int count> in the Cat class.
The reason this works across different instances of Cat (instead of a new variable <int count> being created each time a new Cat is created) is because it is a static variable. Static means only one instance of it exists and is shared across all instances of the Cat class. It is created when the first instance of Cat is declared.
The other part that is important is that the <count> variable is public. Public means that it can be accessed outside of the class Cat. This is why you can call <cat1.count> to access the variable directly. If it was private, you would need a public method like <public int getCatCount()> to return the value of <count>. You would do that by calling <cat1.getCatCount();>. Class variables are typically restricted to private access to provide more control over what has access and how that access functions.
+1