当前位置: 首页 > Thinking in Java > 正文

第10章–内部类_ 静态内部类 (嵌套类)

静态内部类和普通内部类区别

(1) 普通内部类中默认含有外围类的引用,

    所以一个普通内部类必须要链接一个外围类的对象,

    这样普通内部来就不存在 任意的静态成员了(也不能包含static的内部类).

    (因为静态成员都是使用类来访问的,假如普通内部类能够包含静态成员,

    而访问这些静态成员时,又需要外围类的对象,这样就与静态成员用类访问相抵触.)

(2) 静态内部类切断和外围类对象之间的联系,不存在对外围类对象的应用.

    所以,静态内部类可以包含任何的静态对象,

    但是,静态内部类只能访问它的外围类的静态成员.

(3) 创建普通内部类,使用 外围类对象.new 内部类()的方式,

    创建静态内部类,不能用这种方式,只能用 new 外围类.内部类()的方式.

(4) 定义内部类类型是,静态内部类 只能用 [外围类.内部类 对象名] 方式.

    普通内部类可以直接使用 内部类定义,

    但是 使用 [外围类.内部类 对象名]方式看起来更清楚

public interface Contents
{
  int value();
}

public interface Destination
{
  String readLabel();
}

class TestParcel11
{
  private int iCommon=0;
  private static int iStatic = 0;
  public static class ParcelContents implements Contents
  {
    private int i = 11;
    private int iInner = iStatic; //静态内部类只能访问 外围类的静态成员
    public int value()
    {
      return i;
    }
  }

  class CommonInnerClass
  {
    class ThressLevel
    {
      
    }
    private int i = 11;

    public int value()
    {
      return i;
    }
  }

  static class ParcelDestination implements Destination
  {
    private String label;

    private ParcelDestination(String whereTo)
    {
      label = whereTo;
    }

    public String readLabel()
    {
      return label;
    }

    // Nested classes can contain other static elements:
    public static void f()
    {
    }

    static int x = 10;

    //静态内部类内部,也可以有静态内部类,但是普通内部类不能包含任何静态成员
    static class AnotherLevel
    {
      public static void f()
      {
      }
      static int x = 10;
    }
  }

  public static Destination destination(String s)
  {
    return new ParcelDestination(s);
  }

  public static Contents contents()
  {
    return new ParcelContents();
  }

} 

public class Parcel11
{
  public static void main(String[] args)
  {
    TestParcel11 tp = new TestParcel11();
    Contents c = TestParcel11.contents();

    //必须明确指定 TestParcel11.ParcelContents 这种方式 定义变量类型
    TestParcel11.ParcelContents pc = new TestParcel11.ParcelContents();
    // 创建静态内部类,只能用 new 外围类.内部类()的方式.
    Contents pc2 = new TestParcel11.ParcelContents();
    //TestParcel11.ParcelContents pc1 = tp.new ParcelContents();
    // 上面使用普通内部类方式 创建static(嵌套)内部类对象反而不行
    TestParcel11.CommonInnerClass tc = tp.new CommonInnerClass();
    Destination d = TestParcel11.destination("Tasmania");
  }
}

 

赞 赏

   微信赞赏  支付宝赞赏


本文固定链接: https://www.jack-yin.com/coding/thinking-in-java/2362.html | 边城网事

该日志由 边城网事 于2013年07月19日发表在 Thinking in Java 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: 第10章–内部类_ 静态内部类 (嵌套类) | 边城网事
关键字: ,

第10章–内部类_ 静态内部类 (嵌套类) 暂无评论

发表评论

快捷键:Ctrl+Enter