What Are Inner Classes
What Are Inner Classes
• It's like a class inside another class, just as you can have a box inside another box.
• It is a way of logically grouping classes that are only used in one place:
• It increases encapsulation:
• Let's call it the "Class within a Method." It's like a box created inside a
specific method of the OuterClass.
• Pattern:
class OuterClass {
// Some code and variables in the OuterClass
void someMethod() { // Some code in the method
class LocalInnerClass {
// Some code and variables in the LocalInnerClass } /
// More code in the method
}
}
• Explanation:The OuterClass is the big box, and the someMethod() is like a
compartment inside it.The LocalInnerClass is a small box that's created and used only
within the someMethod() of the OuterClass.It's a way to keep related functionality
together and hidden within the method, not accessible from outside.
Real-Life Analogy & Demo
• Real-Life Analogy: *A Kitchen and a Cutting Board*Think of a kitchen
(OuterClass) where you're preparing a meal. You take out a cutting
board (Local Inner Class) to chop vegetables.
• The cutting board is only needed within the kitchen and doesn't
serve any purpose outside of it. It's a temporary helper inside the
kitchen. In this analogy, the kitchen is the OuterClass, and the cutting
board is the Local Inner Clas
Anonymous Inner Class:
• Let's call it the "Mystery Class." It's a class without a name, and it's created and used on the
fly.
• Pattern:
class OuterClass
{ // Some code and variables in the OuterClass