35 内部类和匿名类---Mar老师笔记

来源:互联网 发布:淘宝网魔豆妈妈店铺 编辑:程序博客网 时间:2024/06/18 14:34

内部类

class A { int i;  class B{    int j;int funB(){ int result = A.this.i + this.j;         //外部类A .this return result;}    }}//内部类可以使用A中的成员变量。并不意味着继承了A,只是能使用成员变量,不能拥有A的成员变量//你要想使用外部类的变量    就要写 A.this.i + this.

实现内部类的对象

class Test{    public  static void main(String args){A a = new A();A.B b = a.new B();//内部类d点外部类  a.i = 2;b.j = 3; int result = b.funB();System.out.pritln(result); }}

运行结果为:5

 

匿名类

//A.javainterface A{    public void doSomething();}
//B.javaclass B{    public void fun(A a)    {        System.out.println("B类的fun函数");        a.doSomething();    }}
//Test.javaclass Test{    public static void main()    {        B b = new B();        b.fun(new A()        {            public void doSomething()            {                System.out.println("匿名内部类");            }        });    }}

运行结果:


原创粉丝点击