内部类

来源:互联网 发布:机械臂编程 编辑:程序博客网 时间:2024/06/06 14:25
什么是内部类?

就是将类写在其他类的内部,可以写在其他类的成员位置和局部位置,这时写在其他类内部的类就称为内部类。

比如汽车

在描述汽车时,汽车中还包含这发动机,这时发动机就可以使用内部类来描述。

代码:

class 汽车 { //外部类

    class 发动机 { //内部类

}}


匿名内部类

格式:

new  父类或接口 (){

       //进行方法重写

};


代码:

//定义接口类型

interface  Inter{

    void   show();}

class  Outer{

     public  static  Inter  method(){

        return   new   Inter(){

               public  void   show(){

                     System.out.println("HelloWorld");

}}}

 }

class  OutDemo{

public  static  void   main(String[]  args){

        Outer.method().show();}}

打印结果:
HelloWorld



0 0