匿名类如何使用“扩展”或“实现”?

| 匿名类如何扩展超类或实现接口?     
已邀请:
匿名类必须像其他Java类一样扩展或实现某些内容,即使它只是“ 0”也是如此。 例如:
Runnable r = new Runnable() {
   public void run() { ... }
};
这里,“ 2”是实现“ 3”的匿名类的对象。 匿名类可以使用相同的语法扩展另一个类:
SomeClass x = new SomeClass() {
   ...
};
您不能做的就是实现多个接口。您需要一个命名类来做到这一点。但是,匿名内部类和命名类都不能扩展多个类。     
匿名类通常实现一个接口:
new Runnable() { // implements Runnable!
   public void run() {}
}

JFrame.addWindowListener( new WindowAdapter() { // extends  class
} );
如果您要确定是否可以实现2个或更多接口,那我认为那是不可能的。然后,您可以创建将两者结合在一起的专用接口。虽然我无法轻易想象为什么您希望匿名类具有该类:
 public class MyClass {
   private interface MyInterface extends Runnable, WindowListener { 
   }

   Runnable r = new MyInterface() {
    // your anonymous class which implements 2 interaces
   }

 }
    
匿名类总是扩展超类或实现接口。例如:
button.addActionListener(new ActionListener(){ // ActionListener is an interface
    public void actionPerformed(ActionEvent e){
    }
});
此外,尽管匿名类不能实现多个接口,但是您可以创建一个扩展其他接口的接口,并让您的匿名类来实现它。     
// The interface
interface Blah {
    void something();
}

...

// Something that expects an object implementing that interface
void chewOnIt(Blah b) {
    b.something();
}

...

// Let\'s provide an object of an anonymous class
chewOnIt(
    new Blah() {
        @Override
        void something() { System.out.println(\"Anonymous something!\"); }
    }
);
    
匿名类在创建其对象时正在扩展或实现 例如 :
Interface in = new InterFace()
{

..............

}
在这里,匿名类正在实现Interface。
Class cl = new Class(){

.................

}
在这里,匿名类扩展了抽象类。     
我猜没有人理解这个问题。我想这家伙想要的是这样的:
return new (class implements MyInterface {
    @Override
    public void myInterfaceMethod() { /*do something*/ }
});
因为这将允许类似多个接口的实现:
return new (class implements MyInterface, AnotherInterface {
    @Override
    public void myInterfaceMethod() { /*do something*/ }

    @Override
    public void anotherInterfaceMethod() { /*do something*/ }
});
确实,这真的很好;但这在Java中是不允许的。 您可以做的是在方法块中使用局部类:
public AnotherInterface createAnotherInterface() {
    class LocalClass implements MyInterface, AnotherInterface {
        @Override
        public void myInterfaceMethod() { /*do something*/ }

        @Override
        public void anotherInterfaceMethod() { /*do something*/ }
    }
    return new LocalClass();
}
    

要回复问题请先登录注册