内部类和匿名类

1.如何调用内部类:

class TestInnerClass{

    public static void main( String[] args ){

        Parcel p = new Parcel();//新建一个Parcel对象

        p.testShip();                   //测试

        Parcel.Contents c = p.new Contents(33);

        Parcel.Destination d = p.new Destination( "Hawii" );

        p.setProperty( c, d );

        p.ship();

    }

}

class Parcel {

    private Contents c;

    private Destination d;

    class Contents {

        private int i;

        Contents( int i ){ this.i = i; }

        int value() { return i; }

      }

      class Destination {

         private String label;

        Destination(String whereTo) {label = whereTo;}

        String readLabel() { return label; }

      }

      void setProperty( Contents c, Destination d ){

        this.c =c; this.d = d;

      }

  void ship(){

    System.out.println( "move "+ c.value() +" to "+ d.readLabel() );

  }

  public void testShip() {

    c = new Contents(22);

    d = new Destination("Beijing");

    ship();

  }

}


2.内部类中使用外部成员

public class TestInnerThis

{   

public static void main(String args[]){

    A a = new A();

    A.B b = a.new B();

    b.mb(333);

    }

}

class A

{

private int s = 111;

public class B {

    private int s = 222;

    public void mb(int s) {

        System.out.println(s); // 局部变量s

        System.out.println(this.s); // 子类字段s

        System.out.println(A.this.s); //  父类字段s

    }

    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,767评论 18 399
  • 多态 任何域的访问操作都将有编译器解析,如果某个方法是静态的,它的行为就不具有多态性 java默认对象的销毁顺序与...
    yueyue_projects阅读 994评论 0 1
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,934评论 0 23
  • 最近有很多朋友问我关于公众号的事情,还有的问我公众号是什么,今天就单独出来一篇说一下微信公众号。 公众号是什么: ...
    狂人包阅读 612评论 2 5