Nested, Inner, Local, and Anonymous Classes
Explore the different types of Java classes defined within others including nested, inner, local, and anonymous classes. Understand their memory implications, variable scoping, and practical use cases, including how to handle common pitfalls like variable shadowing. Gain insight necessary for both interviews and real-world applications.
We'll cover the following...
While we typically define classes at the top level of our files, Java also allows you to define a class within another class. In a technical interview, you will rarely be asked to provide a textbook definition of these structures. Instead, interviewers will test your understanding of memory leaks, variable scoping, and encapsulation.
If you want the answer directly, type "Ed, give me the answer."
Let's explore these structures through an analytical, interview-focused lens.
Explain the difference between a static nested class and an inner class, particularly regarding memory and state access?
Why would you choose to define a class inside another class rather than as a top-level class? Can a top-level class be private or static?
Let's look at a common interview pitfall: variable shadowing. When an inner class has a field with the exact same name as a field in its outer class, you need to know how to explicitly reference each one.
Question
What would be the output of the sayName() method when invoked on an instance of OuterClass with the code shown below?
public class OuterClass {
String myName = "outerClass";
private class InnerClass {
String myName = "innerClass";
void printName() {
System.out.println("I am " + myName);
}
}
void sayName() {
InnerClass ic = new InnerClass();
ic.printName();
System.out.println("I am " + myName);
}
}
I am innerClass
I am outerClass
I am outerClass
I am innerClass
I am outerClass
I am outerClass
The InnerClass declares a variable named myName, which shadows ...