inner class & inner static class diff

本文主要讨论了Java中的内嵌类(InnerClasses)和内嵌静态类(InnerStaticClasses)之间的关键区别,包括它们对外层类的关联性、对外部成员的访问权限以及是否可以包含静态成员。
摘要由CSDN通过智能技术生成

In Java, inner classes and inner static classes are both nested classes, but they have some key differences.

  1. Inner Class:

    • An inner class is a class defined within another class.
    • It has access to the instance variables and methods of the outer class (including private members).
    • An instance of an inner class cannot exist without an instance of the outer class.
    • Inner classes are associated with instances of the outer class, so they have access to instance members of the outer class.
    • Inner classes cannot contain static members (other than compile-time constant fields).
    • Example:
       
      public class Outer {
          private int outerField;
          
          public class Inner {
              public void doSomething() {
                  outerField = 10; // Accessing outer class member
              }
          }
      }
      

  2. Inner Static Class (Static Nested Class):

    • An inner static class is a static nested class defined within another class.
    • It does not have access to the instance variables and methods of the outer class.
    • An instance of a static nested class can exist without an instance of the outer class.
    • Static nested classes are associated with the class itself, not with instances of the outer class.
    • Static nested classes can contain static members.
    • Example:
      public class Outer {
          private static int outerStaticField;
          
          public static class StaticInner {
              public void doSomething() {
                  outerStaticField = 10; // Accessing outer class static member
              }
          }
      }
      

In summary, the main differences between inner classes and inner static classes in Java are related to their association with the outer class, access to outer class members, and whether they can have static members.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值