Anonymous classes and non-default constructors

I've got a class with only one constructor and that takes an argument. In another class, I want to have an anonymous class that extends this class with something like:
new MyClassWithoutDefaultConstructor(myConstuctorArg) {...}
However, I get a "The constructor MyClassWithoutDefaultConstructor() is undefined".
As a workaround I can create a local class (not anonymous) that extends MyClassWithoutDefaultConstructor and then includes a default constructor which passes my arg to the super constructor. But this is rather messy.
Am I missing something?

The following works fine for me (prints 5):
public abstract class Test
    private final int parameter;
    public Test(int parameter)
        this.parameter=parameter;
    public int getParameter()
        return parameter;
    public abstract int getSomething();
    public static void main(String[] args)
        Test test=new Test(3)
            public int getSomething()
                return getParameter()+2;
        System.out.println(test.getSomething());
}You say your anonymous class is in a different class to the one it extends - what is the access modifier on the constuctor you are calling in the base class? Is the constructor visible from the class containing the anonymous class? Can you post a concise example that produces the compiler error that you are getting?

Similar Messages

  • ConstructorDoc always shows a non default constructor

    If the source file has no explicite constructor, the ConstructorDocs of ClassDoc always hold a non default constructor as it seems. If there is an explicite coded constructor, the position of the constructor points to the right position in the file. If there is no constructor in the source, it points to the class declaration. Is this a javadoc bug or has anybody seen this problem before?

    I believe, all you need is to check the method: MemberDoc.isSynthetic() It is inherited by ConstructorDoc from the com.sun.javadoc.MemberDoc interface.
    This method is provided specifically to know (and filter out when needed) if the member is implicitly synthesized by the compiler.
    Regards,
    Leonid Rudy
    http://www.docflex.com

  • Creating an instance of a class with no default constructor

    Hello gurus,
    I wrote my own serialization and RMI protocol for both C++ and Java that follows closely what the default Java version does. I'm trying to recreate an object on the Java side that was sent over the wire. The first step is to create an instance of the class. How do I create an instance of a class that has no constructor (i.e. the only instances are static, created by the class itself and returned by static methods) or one that has no default constructor (like Integer)? The Java serialization seems to support it but the reflection API doesn't seem to have any support for this (i.e. Class::newInstance() and Constructor::newInstance()). It seems that through the standard API you can only create an object via one of its constructors. There must be a "hidden" method somewhere that allows the Java serialization to create an object without calling a constructor - where is it?
    Dominique

    There must be a "hidden" method
    somewhere that allows the Java serialization to create
    an object without calling a constructor - where is
    it?You are correct, the way in which the Serialization creates Objects is "hidden" deep within the runtime.
    If it were not hidden, you would be able to find it, and use it to violate the integrity of the VM.

  • Grid control and non-default listener

    I have oem 10.2.0.5 on linux redhat 5
    i have a series of databases with 2 oracle homes on solaris.
    1. we use virtual IPs instead of the host ip. so one IP for each database. This is due to our active/passive cluster. I have read the documentation on this. I was able to configure for this by taking the tnsnames file and using that in the target configration.
    My problem now is that the OEM sees my listener as being down. I think this is because it is looking for the default listener on port 1521. We have 1 listener per database and they are on non-default ports. This is for our active/passive failover.
    how do I configure the target to look for the correct listener? so I do not have a listener called listner.
    My listener has the same name as the database name and is on the same port as my database.

    Guess2 wrote:
    I have oem 10.2.0.5 on linux redhat 5
    i have a series of databases with 2 oracle homes on solaris.
    1. we use virtual IPs instead of the host ip. so one IP for each database. This is due to our active/passive cluster. I have read the documentation on this. I was able to configure for this by taking the tnsnames file and using that in the target configration.
    My problem now is that the OEM sees my listener as being down. I think this is because it is looking for the default listener on port 1521. We have 1 listener per database and they are on non-default ports. This is for our active/passive failover.
    how do I configure the target to look for the correct listener? so I do not have a listener called listner.
    My listener has the same name as the database name and is on the same port as my database.Your database isn't "on" a port, so the fact that you make a statement like "My listener . . . is on the same port as my database." indicates you don't yet have a clear understanding of the relationship of the listener to the database. The fact that you would name your listener the same as your database further indicates you don't yet have a clear understanding of the relationship of the listener to the database.
    The database (actually, we're talking about the instance) really has no inherent relationship to the listener. The listener is just a connection broker. One listener, listening on one port, can service requests for multiple databases, even multiple versions (9.x, 10.x) databases, even databases running out of different homes. For that reason alone, I consider it bad practice to name a listener the same as a database. That implies a relationship that simply doesn't exist. Only under extraordinary circumstances would it be necessary to have more than one listener running on a server, regardless of how many database instances may be on that server. And for that reason it really doesn't make much sense to name your listener anything but the default - "listener".
    You configure your listener to listen on a certain ip and port. You configure your clients (via tnsnames or other naming method) to send connection requests to the ip and port the listener was configured to listen for, requesting a connection to a service name the listener knows about. The listener knows about service names either through coding in the SID_LIST section of listener.ora, or through self-registration by the instance.
    I worked with active/passive clusters with virtual IP's a few years ago and there was really nothing special I had to do as far as the databases, clients, or listeners.

  • Administration Node and non-default certificate

    Hello,
    We are running our administration server on one host, and we have multiple other hosts configured as administration nodes. We used our company CA to generate a server certificate for our administration server, and that appears to be working fine. We tried to do the same thing on our administration nodes, and something curious is happening.
    I used certutil -R to generate a CSR and private key. I then took the generated CSR, obtained a signed certificate from our company CA, then used certutil -A -t u,u,u to install it (and certutil -A -t CT,, to install the CA cert itself). Running certutil -L, I see that in addition to the default Admin-CA-Cert and Admin-Server-Cert our company CA cert and the newly signed cert show up. So far, so good.
    Next, I modified the server.xml to specify the server-cert-nickname as that assigned to my new cert.
    To put these changes into effect, I stop and start the admin server, but upon doing so, I see this message:
    warning: LCM0006: Lifecycle module [AdminLifecycleModule] threw ServerLifecycleException [com.sun.web.admin.exceptions.AdminException: ADMIN3668: Cannot start an unregistered node. Register with an administration server. ]
    OK, so I run wadm register-node to re-register the admin node (presumably it needs to tell the admin server about our new certificate) and then start the admin server again, and it starts. Problem is, the act of running wadm register-node has reset the server-cert-nickname back to the default (Admin-Server-Cert) and even more bizarre, has deleted both our local CA and my new certificate from the certificate & key database.
    How do I - or is it even possible to - run my admin nodes with certs signed by our company CA?
    Thanks,
    Bill

    Hi,
    Can u explain the problem elaborately
    Thanks,
    Raj_indts
    Developer Technical Support
    Sun Microsystems
    http://www.sun.com/developers/support"

  • Multiple instances of one anonymous class

    Hi,
    I am implementing the Command pattern for an interpreter. I've created a Command class to describe the common behavior of all commands and create anonymous classes to manage the few exceptions I have. This design was chosen because I have numerous commands very similar and only a few exception, and I didn't wanted to create one class by command (the ration exception/normal is really low).
    registerCommand(new Command("commandName1", specificParameters...));
    registerCommand(new Command("commandName2", specificParameters...));
    registerCommand(new Command("exception3", specificParameters...)
        protected void execute()
          exceptional treatment...
    registerCommand(new Command("commandName4", specificParameters...));I came to the point that I have two exceptions that extend the Command class in the same way and I was asking if it is possible to create two object instances of the same anonymous class?
    Or asked differently, can one confirm that generally, anonymous classes object instances are unique?
    Thanks

    OK, perhaps I wasn't clear enough...
    Let's go with an example:
    registerCommand(new Command("exception3", specificParameters...)
        protected void execute()
          x = 1;
    registerCommand(new Command("exception4", specificParameters...)
        protected void execute()
          x = 1;
      });This code fragment creates 2 objects instances of 2 different anonymous classes. You can see that these classes have exactly the same definition (but are different), and the 2 instances are different (at least because of new instruction and that the constructor arguments are different, select the whatever reason you like).
    This new Command(..) {...} syntax defines in the same instruction an instance and an anonymous class. I would like to define an anonymous class and create 2 instances from the same anonymous class. I feel no need to name the class as only 2 instances will ever been created. And I was wondering if it is possible...
    I hope it's clearer now :)

  • Static nested class VS non-static nested class ??

    we know static method can be called without creating an object and static variables are shared among objects.
    what is the difference between static nested class and non-static nested class ? When do we use them? what is the advantages of static nested class over non-static nested class in term of performance?

    From the JLS, chapter 8:
    A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.
    This chapter discusses the common semantics of all classes-top level (?7.6) and nested (including member classes (?8.5, ?9.5), local classes (?14.3) and anonymous classes (?15.9.5)).
    So "nested" iff "not top level".From the JLS, chapter 8:
    An inner class is a nested class that is not explicitly or implicitly declared static.
    So a "static" nested class is a bit redundant, since a "non-static" nested class -- a nested class is either static or it isn't -- is more specifically referred to as an "inner class". That's my story and I'm sticking to it. :o)
    ~

  • Default Constructor Help?

    class A {
    public A() {
    public A(int) {
    //--main method--
    }This is an assignment that I'm having some trouble with So let's say I have class A and the default constructor, as well as a constructor that takes an int. The default A constructor is supposed to have an object created by a call to the default constructor of objects, java.lang.Object. However, if I try to refer to the default Object() constructor by using super();, it creates a NullPointerException error (obviously). So is there some sort of default object or something that I'm supposed to use?
    Thanks for all the help :)

    I mean it generates the error during runtime; i can compile it okay.Sorry, I missed that you said it was a NullPointerException.
    For example, it seems to generate the error on the line A.getClass(); even though I don't think it should.That line isn't in the code you posted. The same thing applies really: post a brief example that gives the runtime error along with the exact stack trace that is produced.

  • Access fo Method parameters to Anonymous Class ?

    Can somebody please provide some more information on the statement below? I am also searching for some sample code implementations of it. It would help the cause better.
    +"Methods of the object of the anonymous class need access to final local variables and method parameters belonging to the method in which the anonymous class is defined. "+
    Thanks in Advance

    We're concerned here with "local" classes, i.e. classes defined inside methods (not all anonymous classes are local, and not all local classes are anonymous).
    The thing about local classes is that, unlike local variables etc., instances of a local class may survive the method returning. For example a local class might be a listener which gets added to a swing component, it could be a Runnable that get's launched as a thread.
    Local classes get to access local variables and parameters of the method in which they are declared but the variables or parameters have to be declared final because, since the class needs to be able to access the value of the local variable even after the method exits, and the variable ceases to exist, what actually happens it that the value of the variable is copied into a special field of the anonymous class, and if the variable could be changed after the class was defined, the two copies would then disagree.

  • 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.

  • Best practice for class and constructors

    I'm writing a small utility class that has a private member that is a List. I'm troubled when I think about where this List should be created - in the declaration of the reference or in the default constructor - thus having all other constructors call the default.
    Should I have:
    public Class Foo() {
        private List myList = new ArrayList();
      public Foo() {
      public Foo(String myFoo) {
      public Foo(String[] myFoo) {
      // more methods....
    }or would it be better to code it as:
    public Class Foo() {
        private List myList;
      public Foo() {
        myList = new ArrayList();
      public Foo(String myFoo) {
        foo();
       // other stuff
      public Foo(String[] myFoo) {
        foo();
       // other stuff
      // more methods....
    }In the first option, I know from putting a watch on myList that it stays undefined until any one of the constructors in called. This would seem to me to be the best approach as it doesn't require future additional constructors to have to be written to specifically call the default constructor just to get the ArrayList created. What's typically done in this situation? Which one is considered "good form" or is there a better way?

    I'm writing a small utility class that has a private
    member that is a List. I'm troubled when I think
    about where this List should be created - in the
    declaration of the reference or in the default
    constructor - thus having all other constructors call
    the default.It's not done this way - you have to call this().
    I think the better solution is to have the creation and initialization of the List in the most specific constructor, and have the default call that:
    public class Foo
        private List myList;
        public Foo()
            this(Collections.EMPTY_LIST);
        public Foo(List newList)
            this.myList = new ArrayList(newList);
    }%

  • Using Class and Constructor to create instances on the fly

    hi,
    i want to be able to create instances of classes as specified by the user of my application. i hold the class names as String objects in a LinkedList, check to see if the named class exists and then try and create an instance of it as follows.
    the problem im having is that the classes i want to create are held in a directory lower down the directory hierarchy than where the i called this code from.
    ie. the classes are held in "eccs/model/behaviours" but the VM looks for them in the eccs directory.
    i cannot move the desired classes to this folder for other reasons and if i try to give the Path name to Class.forName() it will not find them. instead i think it looks for a class called "eccs/model/behaviours/x" in the eccs dir and not navigate to the eccs/model/behaviours dir for the class x.
    any ideas please? heres my code for ye to look at in case im not making any sense:)
    //iterator is the Iterator of the LinkedList that holds all the names of the
    //classes we want to create.
    //while there is another element in the list.
    while(iterator.hasNext())
    //get the name of the class to create from the list.
    String className = (String) iterator.next();
    //check to see if the file exists.
    if(!doesFileExist(className))
    System.out.println("File cannot be found!");
    //breake the loop and move onto the next element in the list.
    continue;
    //create an empty class.
    Class dynamicClass = Class.forName(className);
    //get the default constructor of the class.
    Constructor constructor = dynamicClass.getConstructor(new Class[] {});
    //create an instance of the desired class.
    Behaviour beh = (Behaviour) constructor.newInstance(new Object[] {});
    private boolean doesFileExist(String fileName)
    //append .class to the file name.
    fileName += ".class";
    //get the file.
    File file = new File(fileName);
    //check if it exists.
    if(file.exists())
    return true;
    else
    return false;
    }

    ok ive changed it now to "eccs.model.behaviours" and it seems to work:) many thanks!!!
    by the following you mean that instead of using the method "doesFileExist(fileName)" i just catch the exception and throw it to something like the System.out.println() ?
    Why don't you simply try to call Class.forName() and catch the exception if it doesn't exist? Because as soon as you package up your class files in a jar file (which you should) your approach won't work at all.i dont think il be creating a JAR file as i want the user to be able to create his/her own classes and add them to the directory to be used in the application. is this the correct way to do this??
    again many thanks for ye're help:)

  • Selective member import/export using dllexport and default constructor

    We can only export some methods in the class(https://msdn.microsoft.com/es-es/library/8d7d1303-b9e9-47ca-96cc-67bf444a08a9%28v=vs.100%29)
    What if we export only some methods in the class and not exported the default constructor(Will it get generated by the compiler in external app which use this dll?).The class may have some private data member as well which are not exposed in the published
    header file(Which we distribute with DLL).
    How the memory gets allocated to those private data members which are not exposed as the default constructor is not exported? 
    Niranjan

    We can only export some methods in the class(https://msdn.microsoft.com/es-es/library/8d7d1303-b9e9-47ca-96cc-67bf444a08a9%28v=vs.100%29)
    What if we export only some methods in the class and not exported the default constructor(Will it get generated by the compiler in external app which use this dll?).The class may have some private data member as well which are not exposed in the published
    header file(Which we distribute with DLL).
    How the memory gets allocated to those private data members which are not exposed as the default constructor is not exported? 
    Niranjan

  • Super class default constructor

    Hello,
    I want to clear some confusion. I am studying for the exam. In this particular book an example shows that
    Super class has 2 constructor
    public abc() and public abc(int n)
    Sub class has 2 constructor
    public xyz() and public xyz(int n)
    now when an instance is created for the subclass
    xyz t = new xyz(1)
    It will invoke the super class no argument constructor eventhough a default constructor exist in subclass?
    Regards,
    adil

    Here are the rules for constructors--"ctors" because I'm lazy. Also, because I'm lazy, "super(...)" and "this(...)" mean any super or this call, regardless of how many args it takes, including those that take no args.
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

  • Reflection: get an instance of a internal class by default constructor

    Hi there
    first the structure (reduced):
    public class ConvertionFactors { //singelton
    private HashMap<String,Class> factors = new HashMap<String,Class>();
    private class M_TO_FT implements DataFilter{
    public double convert(double value) {
    return value*M_IN_FT;
    public DataFilter getFilter(String from, String to)
    String name = from.toUpperCase()+convertionMethodNameSeparator+to.toUpperCase();
    Class c = factors.get(name); //retrieve the class
    Object o = c.newInstance(); //generate a instance.... not working
    return (DataFilter)o;
    The problem i want an instance of the internal class without defining a construktor like
    public M_TO_FT(){} because there are many classes like this one :-(
    (that was already working with a constructor that wants an instance of the container class.... thats what i am missing in the call c.newInstance() which uses the default constructor (i gues))
    i want something like
    new M_TO_FT() ; just the reflection version of it which calls the default constructor
    thanks for help

    well i get a Exception like this:
    java.lang.InstantiationException: com.eads.jpinfinity.data.unit.ConvertionFactors$M_TO_FT
         at java.lang.Class.newInstance0(Class.java:335)
         at java.lang.Class.newInstance(Class.java:303)
         at com.eads.jpinfinity.data.unit.ConvertionFactors.getFilter(ConvertionFactors.java:315)
         at com.eads.jpinfinity.data.unit.junit.ConvertionFactorsTest.testGetFilter(ConvertionFactorsTest.java:50)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at junit.framework.TestCase.runTest(TestCase.java:154)
         at junit.framework.TestCase.runBare(TestCase.java:127)
         at junit.framework.TestResult$1.protect(TestResult.java:106)
         at junit.framework.TestResult.runProtected(TestResult.java:124)
         at junit.framework.TestResult.run(TestResult.java:109)
         at junit.framework.TestCase.run(TestCase.java:118)
         at junit.framework.TestSuite.runTest(TestSuite.java:208)
         at junit.framework.TestSuite.run(TestSuite.java:203)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:421)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:305)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:186)
    i think because i never told the method which is the containing class for this internal class. if i defina a constructor in the inner class it always needs a instance of the containter. by calling c.newInstance() there is no relation to the container class and because the inner class cant exist without the outer class it may not be constructed.
    It is possible to get an instance with "new FT_TO_M();" (the traditional way) with the default constructor but jet i have not found a way to get a instance of a inner class with reflection without defining a constructor.

Maybe you are looking for

  • Error when activating DataStore Object

    Hello, We have an ODS object which is in avtive stage in ECC DEV system. When we transport it to ECC QA system it can not be activated and shows follwoing errors : 1) Internal error occurred when writing Message no. D0054 2) Error while saving change

  • One doubt on threads

    Hi Techies, Actually I am having one problem with TableModel and Threads. I have one server application which creates one thread for each client. It has one table that contains one row representing details of one client connection. It adds or deletes

  • HT1937 iphone 3GS carrier always says no service and can't activating

    my iphone 3GS always shows no service each time i use a card. i have just upgrade ios 6.0 and iwant to activate it but because of the sim card i can't activate my iphone 3GS. can anyone help me? everything is accepted...

  • Tax code error while entering Expense Receipts in TRIP transaction

    While entering Expense Receipts in the transaction TRIP (Travel Manager), I get an error saying.. "Entry TAXUSJ V0  does not exist in T007A (check entry)". 1) Please help me understand the cause for this error. As the  Travel Expense system is connec

  • JAI and image dimensions

    Is there a way to get an image's (JPEG, GIF, or TIFF) dimension in inches or mm. I have been able to get the image's pixel width and height but don't know how to convert that number to a usable metric such as mm or inch. I need to add functionality t