内部类和匿名类

2018-04-12  本文已影响0人  Hao12

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

    }

    }

}

上一篇下一篇

猜你喜欢

热点阅读