Anonymous Inner Class (匿名内部类) 是否可以extends(继承)其它类,是否可以implements(实现)interface(接口)吗?

解决方案 »

  1.   

    楼主指的无名内部类实现接口指的是类本身定义的时候实现接口还是直接定义无名内部类的时候实现接口,前者肯定是可以的,后者应该是不行的,光从语法上都不能实现   
      class   A   implements   SomeInterface{...}//这里实现接口肯定是可以的   
      class   Main{   
        ...   
        public   A   f(){   
            return   new   A(){...}//这里定义了一个无名内部类,要实现接口,语法上都是不能实现的   
        }   
      ...   
      }   
      

  2.   

    匿名类本身就是通过继承类或者接口来实现的。但是不能再显式的extends 或者implements了。
    举个例子:
    JFrame frame = new JFrame();
    我们为frame添加窗口事件可以采用如下两种方式: frame.addWindowListener(new WindowListener() {            public void windowOpened(WindowEvent e) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }            public void windowClosing(WindowEvent e) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }            public void windowClosed(WindowEvent e) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }            public void windowIconified(WindowEvent e) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }            public void windowDeiconified(WindowEvent e) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }            public void windowActivated(WindowEvent e) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }            public void windowDeactivated(WindowEvent e) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });这个匿名类就是实现了接口WindowListener
    或者:frame.addWindowListener(new WindowAdapter() {});上面这个匿名类就是继承了WindowAdapter这个抽象类。
      

  3.   

    这是个匿名内部类的例子
    class IsXsg{
    private String name;
    IsXsg(String s){name=s; 
    System.out.print(name);}
    }
    public class NiMingTest{
    public static void main(String[] args){
    new IsXsg("新曙光"){
    public void ShuChu()
    {System.out.println(" is my name.");}
    }.ShuChu();
    //new IsXsg("新曙光");
    }
    }//www.xinshuguang.org
    视频讲解