zoukankan      html  css  js  c++  java
  • java 内部类使用 .this 和 .new

    如果需要生成对外部类对象的引用,可以使用外部类的名字后面紧跟圆点和this,这样产生的引用自动地具有正确的类型,这一点在编译器就被知晓并受到检查,因此并没有运行时开销

    //: innerclasses/DotThis.java
    // Qualifying access to the outer-class object.
    package object;
    public class DotThis {
      void f() { System.out.println("DotThis.f()"); }
      public class Inner {
        public DotThis outer() {
          return DotThis.this; //这里生成了类DotThis的引用(inference)
          // A plain "this" would be Inner's "this"
        }
      }
      public Inner inner() { return new Inner(); }
      public static void main(String[] args) {
        DotThis dt = new DotThis();
        DotThis.Inner dti = dt.inner();
        dti.outer().f();//这里用类DotThis的引用(inference) 创建类DotThis的对象
      }
    } /* Output:
    DotThis.f()
    *///:~

    要去创建某个内部类的对象,必须字new表达式中提供其他外部类对象的引用,这就需要.new语法,必须使用外部类的对象来创建内部类

    //: innerclasses/DotNew.java
    // Creating an inner class directly using the .new syntax.
    package object;
    public class DotNew {
      public class Inner {}
      public static void main(String[] args) {
        DotNew dn = new DotNew(); 
        DotNew.Inner dni = dn.new Inner(); //这里利用DotNEW的对象生成内部类Inner的对象
        //! DotNew.Inner dni = DotNew.new Inner(); //这样不允许(allow)
      }
    } ///:~
  • 相关阅读:
    序列化和反序列化(2)[Serializable] 转
    http错误列表(转)
    公共Webservice
    序列化和反序列化(1)[Serializable]
    序列化中的[NonSerialized]字段 转
    后台调用前台js
    http的请求和响应过程2
    命名规则
    tsql LastIndexOf
    js产生随机数
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/10219490.html
Copyright © 2011-2022 走看看