Anonymous class instantiation expression with interface implementation??

Is it possible to create an inline anonymous class instatiation expression that can implements an interface?
For example:
Frame myFrame = new Frame() implements WindowListner {
     public void WindowOpened(WindowEvent  e) {}
         +other interface methods....+
}Apparently compiler doesn't like this code:(
I know that I can create an extra named class with the interface, then instantiate it instead. But this is not what I want.
(By the way, if someone wants to know why I want to do this, I say I think this may make my code simpler or look better, that's all:) )

abstract class ListenerFrame extends Frame implements WindowListener {} This look pretty neat:)
I guess I can rewrite my code then:
abstract class FrameWithListener extends Frame
         implements WindowListener{}      //local class
Frame myFrame = new FrameWithListener {
        public void WindowOpened {}
           blah, blah...
}Not sure I can use abstarct class as local class, but otherwise I'll use it as a class member or some sort..
Thank you for the reply
Edited by: JavaToTavaL on Nov 27, 2009 4:04 AM
Edited by: JavaToTavaL on Nov 27, 2009 4:04 AM

Similar Messages

  • Some generic anonymous class overriding methods compile, while others don't

    I have the following (stripped-down) code. The abstract class SessionHandler<T> is used by other code to define and run an operation that needs a session to something. This is best done in my code with anonymous classes, because of the shear number of operations defined. In the EntityOps<T> class, these work great. But, in the last class shown here, SomeClass, the anonymous class definition fails, though the semantics are almost identical. (List<T> vs.List<AnotherClass>) What am I doing wrong here? Or is this a bug in Java?
    Thanks, Tom
    public interface IEntityOps<T> {
        T get();
        List<t> getAll();
    public abstract class SessionHandler<T> {
        abstract T handle(Session session) throws Throwable;
        public final T perform() {
            ... calls handle(session) ...
    // These anonymous class definitions compile fine!
    public class EntityOps<T> implements IEntityOps<T> {
        public T get() {
            T ret = null;
            ret = new SessionHandler<T>() {
                T handle(Session s) throws Throwable {
                    T ret = (some T object calculation);
                    return ret;
            }.perform();
            return ret;
        public List<T> getAll() {
            T ret = null;
            return new SessionHandler<List<T>>() {
                List<T> handle(Session s) throws Throwable {
                    List<T> ret = (some List<T> calculation);
                    return ret;
            }.perform();
    // This anonymous class definition fails with the error:
    // "SomeClass.java": <anonymous someMethod> is not abstract and does not override abstract method handle()
    //     in SessionHandler at line XX, column XX
    public class SomeClass {
        public List<AnotherClass> someMethod() throws {
            List<AnotherClass> ret = null;
            ret = new SessionHandler<List<AnotherClass>>() {
                List<AnotherClass> handle(Session s) throws Throwable {
                    List<AnotherClass> ret = (some List<AnotherClass> calculation);
                    return ret;
            }.perform();
            return ret;
    }

    I added @Override above the abstract method override, and it provides this additional error:
    "HousingConfigImpl.java": method does not override a method from its superclass at line 382, column 17
    I have also reconstructed the code layout in a separate set of classes that have no dependancies, but there's no error coming from these!
    public class CustomThing {
    public interface ISomeInterface<T> {
        List<T> interfaceMethod();
    public abstract class SomeAbstractClass<T> {
        private Class _c = null;
        public SomeAbstractClass(Class c) {
            _c = c;
        protected Class getC() {
            return _c;
        public abstract T methodToOverride(Object neededObject) throws Throwable;
        public final T finalMethod() {
            try {
                return methodToOverride(new Object());
            } catch(Throwable e) {
                throw new RuntimeException(e);
    import java.util.List;
    import java.util.Collections;
    public class SomeInterfaceImpl<T> implements ISomeInterface<T> {
        public List<T> interfaceMethod() {
            return new SomeAbstractClass<List<T>>(CustomThing.class) {
                public List<T> methodToOverride(Object neededObject) throws Throwable {
                    return Collections.emptyList();
            }.finalMethod();
    import java.util.Collections;
    import java.util.List;
    public class SomeOtherClass {
        public List<CustomThing> someMethod() {
            return new SomeAbstractClass<List<CustomThing>>(CustomThing.class) {
                public List<CustomThing> methodToOverride(Object neededObject) throws Throwable {
                    return Collections.emptyList();
            }.finalMethod();
    }So, there's something about my code that causes it to be, somehow, different enough from the example provided above so that I get the error. The only differences in the override method definitions in my actual code are in the return type, but those are different in the example above as well. Here are the class declarations, anonymous abstract class creation statements, and abstract method declarations from the actual code.
    public abstract class SessionHandler<T> {
        abstract T handle(Session session) throws Throwable;
    public class EntityOps<T> implements IEntityOps<T> {
                return new SessionHandler<List<T>>(_mgr, _c, "getAll" + _c.getName()) {
                    List<T> handle(Session s) throws Throwable {
    public class HousingConfigImpl implements IHousingConfigOperations, ISessionFactoryManager {
                ret = new SessionHandler<List<Tenant>>((ISessionFactoryManager)this, Housing.class, "getTenantsInNeighborhood") {
                    List<Housing> handle(Session s) throws Throwable {I can't for the life of me see any syntactical difference between my example and the real code. But, one works and the other doesn't.

  • Listener Interface implementation questions

    Dear all experts,
    I am getting a bit confused of the "standard" way of implementing listener interfaces.
    I found that there are 3 general methods:
    1) create an extra class implementing the interface.
    2) implement the interface as an inner class
    3) using the existing class to implement the inferface :
    eg:
    public class oneofmyclass implement FocusListener
    public oneofmyclass()
    constructor....
    all my other methods.........
    the interface methods......
    Why there are so many ways to do it?
    what's the differences/benefits of each??
    Thx

    I am getting a bit confused of the "standard" way of implementing listener interfaces.
    I found that there are 3 general methods:
    1) create an extra class implementing the interface.
    2) implement the interface as an inner class
    3) using the existing class to implement the inferfaceThere isn't much difference between 1) and 2). The first alternative creates a named inner class
    (that implements the listener interface) while the second creates an anonymous class using that
    listener interface. Alternative 3) exposes the interface to the outer world, i.e. your class may be
    attached to some listener list (in some observable) it really wasn't meant for.
    I prefer 1) or 2) If the actual code for the listener is small I use 2), otherwise I use 1) but that's
    just for readability reasons. I almost never use 3) because I don't want my class to be hooked
    up to any observable it wasn't designed for.
    kind regards,
    Jos

  • Is the "Device Class Definition for Physical Interface Devices" specification implemented in Windows?

    Can I assume that Windows will be able to handle my physical interface device if I follow the "Device Class Definition for Physical Interface Devices" specification while writing the firmware?
    I'm trying to develop a device which handles rumble output from applications such as games. Applications would include e.g. racing games or simulators. I'm hesitant to just clone Xbox 360 Gamepad or Sidewinder USB reports. I'd like to correctly declare my
    device as something on its own while still making use of already implemented OS-specific drivers. The purpose of the mentioned specification is exactly that as far as I can tell. I wasn't able to find concrete information about its level of support though.
    The "USB device class drivers included in Windows" page (sorry I'm not allowed to post links yet..) seems to link to WinUSB which I'm not sure what to do with.

    Thanks for your response. Well if everything was implemented at that time and it's still available it should be fine since the specification document's last version is dated 1999. I was just hoping there would be any form of documentation whether it's
    supported and by which degree so I don't go through the trouble of figuring out how the firmware should be written according to the specification just to find out there is no OS driver implementation for it which would render my work more or less useless.
    So I suppose I'm forced to go the trial and error path?

  • Trouble with interface class

    Hi there,
    for a school project we're building a helicopter which can be controlled via the computer. We're going to connect some wires to the remote control of the helicopter and the wires we also connect to a LabJack (a digital/analog converter). Via java we can give signals to this labjack and control so the helicopter. Only one thing: I've downloaded the library for labjack for java. You can see this labrary, it called LabJackJava: http://www.teravation.com/downloads/LabJackJava.zip
    In it is a few classes and one of them is called LabJack (this is in fact a interface). In the interface there is a method called: void setAO(int channel, float value) throws LabJackException;
    This method I'm going to need to set the voltage on the wires. For compiling I use the program BlueJ (which is a object-orientated compiler). But because the the class LabJack is a interface, I cannot call the method setAO(). How can I solve this?? I also had some trouble with the System.loadLibrary("ljackj"); in the class LabJackDriver. I copied the file ljackj.dll into the folder system32 (windows) and it still doesn't work... Is this dll essential for the working of the class LabJack??? How can I solve this???
    Please help me!!
    Thanks!
    Héctor van den Boorn

    This is a forum for the Java programming language, not for every program and library ever written in Java. The LabJack site has a support area and forum, which should be the right place to seek a solution.
    That said, the documentation indicates that you obtain a LabJack reference from the appropriate method of LabJackFactory. The reference returned will be that of a platform dependent concrete class that implements the interface.
    db
    edit Oh, I see you have a history of not replying to responses on your posts. This was exceptionally bad, 9 responses and not a peep out of you.
    [http://forums.sun.com/thread.jspa?threadID=5242071]
    Fine. One for the blacklist.
    Edited by: Darryl.Burke

  • No Implementing class registered for the Interface : ES-TransportationOrderSCMExecutionRequest_In

    Dear PI Experts,
    I'm currently working on an integrated solution between TM <=> PI <=>ECC. When I trigger the Shipment creation from TM to ECC, I received an error in the SXMB_MONI of ECC.
    In the XML, I figured the error that No Implementing class registered for the Interface TransportationOrderSCMExecutionRequest_In .
    May I ask you advices on this issue? Is it a mapping error on ECC or PI Side?
    Thanks in advance for you help and advice.
    Kr,
    JP

    Hi JP,
    you can also refer the below wiki and blog
    Step-by-step FTP to ABAP Proxy - Process Integration - SCN Wiki
    ABAP Proxy Protocols: Use Cases and Examples
    regards,
    Harish

  • No implementing class registered for the interface (ABAP interface, request

    Hi,
    Proxy has been generated for the Inbound Message interface and i could see the SXMB_MONI entry in Red on the target system.
    I get the error "No implementing class registered for the interface (ABAP interface, request...."
    regards,
    Chaitanya

    Hi Chaitanya,
    Try the below configuration in SXMB_ADM,if you don't have the authorisations to SXMB_MONI ask BASIS guys to do the below activities.
    Go to SXMB_ADM.
    Execute Integration Engine
    EDIT----
    > Change Global configuration data
    select  Role of Business System as Integration Server
    Thanks,
    Amar.

  • No implementing class registered for the interface

    Hello,
    I know that I'm not the first one posting this problem, but I can't find an appropriate solution for my problem. When I execute the FlightSeatAvailabilityCheck scenario I got the following error:
    Unable to check flight availability.       
    Error Type:      XI system error
    Error Details:      No implementing class registered for the interface (type ifmmessif, name FlightSeatAvailabilityQuery_Out, namespace http://sap.com/xi/XI/Demo/Agency )
    I have to say that I accidently deleted the proxy but I have recreated and activated the concerning proxy (CO_SXIDAG_FSA_QUERY) and still get the error. I read in this thread: XI 3.0 Demo: Unable to check flight availability: XI System Error that it would help to create a RFC in sm59. Why do I have to do this although I'm using proxies?
    And does it make a difference in which client I create and activate the proxies?
    Regards
    Marc

    i tried following solution also from old messages in SDN -
    Go to SXMB_ADM.
    Execute Integration Engine
    EDIT-> Change Global configuration data
    Select the Role of Business System is Integration Server
    Again started getting error-PROXY_NOT_ALLOWED_ON_IS:
    Proxy calls are not permitted on sender or receiver side on the IS (client)</SAP:Stack>
    But again  one of the messages in SDN suggests to change Global configuration data,
    EDIT-> Change Global configuration data
    Select the Role of Business System is Application system.
    it seems it's going in loop....

  • Proxy :No implementing class registered for the interface

    <b>Hi
       I am executing an Out bound proxy from client 101.
    when i execute the proxy, i could see the following error in moni.
    error info----
    No implementing class registered for the interface (type ifmmessif, name PORequest_Out, namespace http://sap.com/xi/3A4/Purchasing/proxytoRfc)
    end of error info----
    Any tips fro the experts??
    Regards</b>chandra<b></b>

    Hi Chandra,
    You need to activate both the classes and the interfaces.
    Try to regenerate and activate once again.
    http://help.sap.com/saphelp_nw2004s/helpdata/en/86/58cd3b11571962e10000000a11402f/frameset.htm
    Also refer the blog mentioned by earlier post.
    Hope this helps,
    regards,
    Moorthy

  • Is the remote interface implemented by some class

    Hi,
    I have a simple question, googled, no help.
    I am trying to udnerstand, where exactly is the remote interface implemented ?
    I mean, i know that it contains all the business methods which have a body in the bean.
    But is the remote interface implemented somewhere ? Is there any class which implements the Remote interface ?
    thanks
    S

    Sarvananda wrote:
    Hi,
    I have a simple question, googled, no help.look better...
    I am trying to udnerstand, where exactly is the remote interface implemented ?
    I mean, i know that it contains all the business methods which have a body in the bean. so, that's what implements it :)
    But is the remote interface implemented somewhere ? Is there any class which implements the Remote interface ?
    the bean class :)
    But the actual implementor is a class generated by the appserver that delegates to the bean class.

  • B32 compiler bug: varargs with anonymous class

    Environment
    SunOS bart 5.10 s10_48 i86pc i386 i86pc Solaris
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0-beta-b32)
    Java HotSpot(TM) Client VM (build 1.5.0-beta-b32, mixed mode)
    javac 1.5.0-beta
    Javac command produces NullPointerException
    javac -source 1.5 -target 1.5 Quick.java (source follows)
    Description
    The problem seems to be use of a varargs constructor while defining
    an anonymous class. Work around is for caller to manually box the
    (varargs) into an array, bypassing convenience of varargs support.
    class Quick
      Quick() {
        Fox fox1 = new Fox(1)                        {}; // compiles
        Fox fox2 = new Fox(new String[] { "hello" }) {}; // compiles
        // NullPointerException not thrown when following 4 lines are
        // commented out.
        Fox fox3 = new Fox(null)            {}; // compiles, but ambiguous?
        Fox fox4 = new Fox()                {}; // javac NullPointerException
        Fox fox5 = new Fox("hello")         {}; // javac NullPointerException
        Fox fox6 = new Fox("hello", "bye")  {}; // javac NullPointerException
    class Fox
      Fox(int a) {
        _keys = new String[0];
      Fox(String... keys) {
        _keys = keys;
      final String[] _keys;
    }

    reported as 4986231

  • Anonymous class - reference to enclosing object

    Hi,
    I have a class (which is in fact an Adapter that implements several interfaces
    for EventListener) that should be instantiated in the code via an anonymous
    class, i.e. like this
    this.addAdapter( new Adapter() {
    // implemented methods here
    Now I have the problem that when I pass the instance of the anonymous class
    later to a method somewhere else, I need a reference to the object which
    instantiated it:
    public class AClass {
    priavte BClass bClass;
    private Adapter adapter;
    public AClass() {
    this.addAdapter( new Adapter() {
    // implemented methods here
    bClass = new BcLass();
    bClass.doSomething
    void addAdpater( Adpater ad ) {
    this.adpater = ad;
    public class BClass {
    public BClass() {
    doSomething( Adapter ad ) {
    // how can I get a reference to the instance
    // of AClass that called this method ?????
    My IDE shows the needed object as member this$0 of the Adpater, so I
    suppose there is some way to get at the reference to this enclosing
    object, but how???
    Thanks in advance for any idea,
    Leif

    If it's possible to get the reference without the adapter explicitly giving it to you, then everything that's been written about read-only adapters is silly, so I would bet that it's not possible.
    Your adapter is written as an inner class, so it has access to all the enclosing object's state. If you can modify the adapter class, you could expose as much of that state as you wanted. Maybe that's as good as the reference for your purposes.
    But maybe not. So the only option I could see is that the adapter itself has a method
    public AClass getEnclosingAClassInstance()
    which returns a reference to the enclosing class. The way to set it might be to make a corresponding set method which AClass calls with 'this' before handing off the adapter to BClass, or by AClass itself providing a getThis method, which the adapter could call. I'm pretty sure you can't get anymore direct access to the enclosing 'this', because the adapter's 'this' shadows it.
    All of which leaves me wondering--why? It's so weird and un-adapter-like that I suspect it's the wrong idiom. But maybe you know something I don't....

  • Calling a Classes constrictor explicitly with out editing the Class

    Hi All,
    I am looking for a way to call the a Classes static constructor of a class so that the static fields get initialized. Here is some pseudo code to illustrate
    class Singleton {
        private static instance = new Singleton();
        private Map map = new HashMap();
        boolean obtainedKey = false;
        private Singleton() {
            //populate map code
        public Singleton getInstance() {
            return instance;
       public Object getVal(String key) {
           obtainedKey = true;
           return map.get(key);
      public getObtainedKey() {
         return obtainedKey;
    class MyClass {
         static Singleton sing = Singleton.getInstance();
         static Object objVal = sing getVal.get("key");
    public static void main(String [] args)  {
          Singleton singMain = Singleton.getInstance();
          MyClass.*SOME_METHOD_ALREADY_IN_JAVA*;
          assert(singMain.getObtainedKey() == true);
    } One solution is to add a method ;
    static void init() {}; to the class MyClass and then to call this method,
    However I would like to find a method somewhere in the java library so I don't have to write a init method.

    I think you really should re-think your architecture if it depends on such strange loops (and personally I've had very bad experiences with static initializer blocks, especially those that can fail).
    But curiousity got the better of me and I dug into the JVM spec. In �2.11 (http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#32316) it says
    Any static initializers declared in a class are executed when the class is initialized (�2.17.4) and, together with any field initializers (�2.9.2) for class variables, may be used to initialize the class variables of the class (�2.17.4).And in �2.17.4 (http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#19075) it says
    Initialization of a class consists of executing its static initializers (�2.11) and the initializers for static fields (�2.9.2) declared in the class. Initialization of an interface consists of executing the initializers for fields declared in the interface (�2.13.3.1).
    Before a class or interface is initialized, its direct superclass must be initialized, but interfaces implemented by the class need not be initialized. Similarly, the superinterfaces of an interface need not be initialized before the interface is initialized.
    A class or interface type T will be initialized immediately before one of the following occurs:
    * T is a class and an instance of T is created.
    * T is a class and a static method of T is invoked.
    * A nonconstant static field of T is used or assigned. A constant field is one that is (explicitly or implicitly) both final and static, and that is initialized with the value of a compile-time >constant expression. A reference to such a field must be resolved at compile time to a copy of the compile-time constant value, so uses of such a field never cause initialization.
    Invocation of certain methods in library classes (�3.12) also causes class or interface initialization. See the Java 2 platform's class library specifications (for example, class Class and package java.lang.reflect) for details.So if you don't want to create and instance or add a method then you can only use (read) or assign a nonconstant static field (the field initialized by the static block should be fine).
    The library functions above are not required to initialize the class, so that won't be much help.

  • How can Anonymous class inherit ?

    I am not much fluent with Inner Classes concept.Only today i read that
    "An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. "
    JLS Classes Page also couldn't fetch me my answer or may be i could not spot it.I think latter.
    I think a in depth study of Inner Classes,Anonymous classes can get me my answer. Can anyone give me any pointers that would clear my doubt ?
    Thank you for your consideration.
    Edited by: amtidumpti on May 1, 2009 12:58 AM

    amtidumpti wrote:
    I am not much fluent with Inner Classes concept.Only today i read that
    "An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. "
    JLS Classes Page also couldn't fetch me my answer or may be i could not spot it.I think latter.
    http://java.sun.com/docs/books/jls/third_edition/html/classes.html
    I think a in depth study of Inner Classes,Anonymous classes can get me my answer. Can anyone give me any pointers that would clear my doubt ?
    Thank you for your consideration.Start writing an anonymous class and you should readily see why it can't do both.
    Have you even tried to implement an anonymous class yet? Please clear my doubt.

  • Where is the anonymous class in this? (lotsa code)

    When I compile ThreadPool.java, I get three classes: ThreadPool.class, ThreadPool$WorkerThread.class, and ThreadPool$1.class. I understand the first two, but I can't figure out where the anonymous class is coming from. Could it be some kind of automatically-generated wrapper class caused by the fact that all accesses to the Queue object are within synchronized blocks? Curiosity attacks!
    Thanks,
    Krum
    ThreadPool.java:
    package krum.util;
    * A thread pool with a bounded task queue and fixed number of worker threads.
    public class ThreadPool {
       protected Queue queue;
    public ThreadPool(int threads, int taskQueueSize) {
       queue = new Queue(taskQueueSize);
       /* create the worker threads */
       for(int i = 0; i < threads; ++i) {
          Thread t = new Thread(new WorkerThread());
          t.setDaemon(true);
          t.start();
    * Queues a task to be executed by this ThreadPool.  If the task queue is
    * full, the task will run in the calling thread.  (Could easily be modified
    * to throw an exception instead.)
    public void doTask(Runnable task) {
       boolean added = false;
       synchronized(queue) {
          if(!queue.isFull()) {
             queue.add(task);
             added = true;
             queue.notify();
       if(!added) task.run();
    * Tests if the task queue is empty.  Useful if you want to wait for all
    * queued tasks to complete before terminating your program.
    public boolean queueEmpty() {
       synchronized(queue) {
          return queue.isEmpty();
    private class WorkerThread implements Runnable {
    public void run() {
       Runnable task;
       while(true) {
          task = null;
          synchronized(queue) {
             try {
                if(queue.isEmpty()) queue.wait();
                else task = (Runnable)queue.getNext();
             } catch(InterruptedException e) { break; }
          if(task != null) task.run();
    } /* end inner class WorkerThread */
    } /* end class ThreadPool */Queue.java:
    package krum.util;
    * Implements a FIFO queue for storage and retrieval of objects.  This class
    * is not synchronized.
    public class Queue {
         /** circular buffer containing queued objects */
         protected Object[] queue;
         /** index of next object to be returned */
         protected int nextReturn;
         /** index in which to store next object inserted */
         protected int nextInsert;
    public Queue(int capacity) {
         queue = new Object[capacity];
         nextInsert = 0;
         nextReturn = 0;
    public boolean isEmpty() { return(queue[nextReturn] == null); }
    public boolean isFull() { return(queue[nextInsert] != null); }
    public void add(Object obj) throws QueueException {
         if(queue[nextInsert] == null) {
              queue[nextInsert] = obj;
              ++nextInsert;
              nextInsert %= queue.length;
         } else throw new QueueException();
    public Object getNext() throws QueueException {
         if(queue[nextReturn] != null) {
              Object obj = queue[nextReturn];
              queue[nextReturn] = null;
              ++nextReturn;
              nextReturn %= queue.length;
              return obj;
         } else throw new QueueException();
    } /* end class Queue */QueueException.java:
    package krum.util;
    public class QueueException extends RuntimeException { }

    I can't explain why it happens, but I've seen this
    behaviour before. I found that it was to do with an
    inner class (WorkerThread in your code) having a
    private constructor - if I made my inner class
    constructor at least package (default) access, then
    the anonymous class was no longer created.
    The generated default constructor for a class has the
    same access modifier as the class, so in your example,
    the default constructor that the compiler generates is
    private.
    I suspect the problem will go away if you either:
    1. Remove the private modifier from the WorkerThread
    class declaration.
    or:
    2. Add a no-args constructor to the WorkerThread
    class, and don't specify an access modifier.Yes, the reason is the private constructor. After decompile using JAD, the reason seems to be: if a private inner class does not explicitly have any constructor, a default no-arguments private constructor is created, and seems this default constructor can't be accessed directly (in source code, it can). So, another no-private constructor (package accessible) is created automatically (with an argument of Object's type), and the
    new WorkThread();is actually like this:
    new WorkThread(null);
    private class WorkThread implements Runnable{
       private WorkThread(){}
       WorkThread(Object obj) {
          this();
    }and I would guess it's using anonymous class tech to achieve this like:
    new WorkThread(null) {
       WorkThread(Object obj){
          this();
    }The JLS should have specified this situation.

Maybe you are looking for