这个问题在这里已有答案:
我是Java的新手。在学习的过程中,我遇到了内部类 - 静态和非静态内部类。虽然我已经了解它们是如何运作的,但我无法弄清楚它们的真正目的!
我要求社区以某种方式清除这种疑问,即使是小孩也会理解。我浏览了多个网站,但他们的解释并没有满足我的查询。
当你想在一个类(class
)中定义一个nested
并且你也想从其他类声明该类的对象时,你需要一个static nested class
。如果您不想在父类之外创建此嵌套类的对象,则不需要static
。
内部类可以具有外部类的属性。请考虑以下示例:
class School {
// school has classroom
// school has a canteen
class Student {
// students can have the access of classroom & canteen
// Students can have their own properties like books, bags
}
class Teachers {
// Teachers can have the access of classroom & canteen
// Teachers can have their own properties like board, staffroom
}
}
内部类实际上只存在以帮助开发人员组织代码;编译器就像任何其他类一样处理内部类,除了内部类具有有限的范围,因此它们被束缚到它们定义的类。此外,内部类可以具有外部类的属性。
有关详细信息,请参阅以下链接以获得更多想法:https://code.tutsplus.com/tutorials/learn-java-for-android-development-inner-classes--mobile-3530