Static Fields Prohibited in Inner Classes: Rationale
Java prohibits the declaration of static fields and methods within inner classes (or ordinary inner classes) due to their inherent instance-dependent nature.
Inner classes, unlike static nested classes, are tied to他們封閉班級的實例。這意味著內部類的每個實例都與封閉類的特定實例都有獨特的關聯。結果,允許在內部類中允許靜態字段在靜態字段所屬的實例中產生歧義。
如果在內部類中允許靜態字段,則沒有明確的方法來確定我所屬的靜態字段的哪個實例。這種歧義可能會導致運行時錯誤和不一致的行為。此外,允許內部類中的靜態字段與基於實例的依賴關係的原理相矛盾。 Since inner classes rely on instances of the enclosing class, it doesn't make sense for them to have static features, which are designed to operate independently of any instance.
class OuterClass { class InnerClass { static int i = 100; // compile error } }
Clarity and consistency:
Prevent ambiguity regarding which instance a static field belongs to。遵守設計原理:
保留內部類的實例依賴性,並避免具有靜態功能的矛盾。免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3