"So, topic number two is static nested classes. Remember that non-static nested classes are called inner classes.
"Let's wrap our heads around what the word static means in the context of a nested class declaration. What do you think?"
"If a variable is declared as static, then only one copy of the variable exists. So, if a nested class is static, then does that mean you can only create one object of that class?"
"Don't let the word static confuse you here. It is true that if a variable is declared as static, then there is only one copy of the variable. But a static nested class is more like a static method in this regard. The word static before the class declaration indicates that the class does not store references to objects of its outer class."
"Ah. Normal methods implicitly store a object reference, but static methods do not. It's the same with static classes, am I right, Ellie?"
"Absolutely. Your quick understanding is commendable. Static nested classes don't have hidden references to objects of their outer class."
class Zoo
{
private static int count = 7;
private int mouseCount = 1;
public static int getAnimalCount()
{
return count;
}
public int getMouseCount()
{
return mouseCount;
}
public static class Mouse
{
public Mouse()
{
}
public int getTotalCount()
{
return count + mouseCount; // Compilation error.
}
}
}
"Let's review this example carefully."
"What variables can the static getAnimalCount method access?"
"Only the static ones. Because it is a static method."
"What variables can the getMouseCount method access?"
"Both the static and non-static ones. It has a hidden reference (this) to a Zoo object."
"That's right. So, the static nested Mouse class, like a static method, can access the Zoo class's static variables, but it can't access non-static ones."
"We can safely create Mouse objects, even if not a single Zoo object has been created. Here's how you can do that:"
class Home
{
public static void main(String[] args)
{
Zoo.Mouse mouse = new Zoo.Mouse();
}
}
"The Mouse class is actually a very ordinary class. The fact that it is declared inside the Zoo class gives it two special features."
1) When creating objects of a nested class (such as the Mouse class) outside the outer class, you must also use the dot operator to specify the name of the outer class.
"Like this, for example: Zoo.Mouse."
2) The Zoo.Mouse class and its objects have access to the Zoo class's private static variables and methods (since the Mouse class is also declared inside the Zoo class).
"That’s it for today."
"So just an additional name and that's it?"
"Yes."
"That's even easier than it seemed at first."
GO TO FULL VERSION