美文网首页
内部类和匿名类

内部类和匿名类

作者: Hao12 | 来源:发表于2018-04-12 06:16 被阅读0次

    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

        }

        }

    }

    相关文章

      网友评论

          本文标题:内部类和匿名类

          本文链接:https://www.haomeiwen.com/subject/uobtkftx.html