Enum declaration in a method

An enum can be declared inside or outside a class, but can't be declared in a method.
Can anyone tell that what is the problem with it. for what reason this restriction exist?
Thanks in advance

Karanjit is right. Nested interfaces and enums both are implicitly static. And their Constants are always (also when defined in top level) implicitly static. As we can't have static types inside a method we can't define enum in a method.
I read in "Sun Certified Programmer for Java 5 Study Guide" written by Bert Bates and Kathy Sierra that if we have following enum:
enum CoffeeSize { BIG, HUGE, OVERWHELMING }then we can think of this enum as a kind of class, that looks something (but not exactly) like this:
class CoffeeSize {
     public static final CoffeeSize BIG = new CoffeeSize("BIG", 0);
     public static final CoffeeSize HUGE = new CoffeeSize("HUGE", 1);
     public static final CoffeeSize OVERWHELMING = new CoffeeSize(
               "OVERWHELMING", 2);
     public CoffeeSize(String enumName, int index) {
          // stuff here
     public static void main(String[] args) {
          System.out.println(CoffeeSize.BIG);
}Also see this code which is compilable:
class HaveEnum {
     enum Colours {
          BLACK, WHITE
     static class StaClass {
          public static final StaClass sc = new StaClass();
     class InstClass {
          public final InstClass ic = new InstClass(); // can't be declared static
public class General {
     public static void main(String[] args) {
          HaveEnum.StaClass hes = HaveEnum.StaClass.sc; // (1)
          HaveEnum.Colours col = HaveEnum.Colours.BLACK; // (2)
          HaveEnum he = new HaveEnum(); // (3)
          HaveEnum.InstClass hei = he.new InstClass().ic; // (4)
}We can have enum constant BLACK in General class (at (2)) in similar way as StaClass constant sc (at (1)). If enum Colours were instant type like InstClass inner class then for having BLACK constant in General we would have to first instantiate HaveEnum class (like at (3)) and then using its object reference we could get BLACK constant (something like this) (like for InstClass at (4)):
HaveEnum he = new HaveEnum();
HaveEnum.Colours col = he.new Colours().BLACK;Note that main() method will throw StackOverflowError at runtime because (4) tries to recursively create another InstClass object.

Similar Messages

  • Variables declared in static methods

    Hi,
    I've got a question. Are variables (primitive and Objects) declared inside
    static methods stored in a same memory space or are the stored separately?
    I'm creating a helper class that contains static methods that canno be placed in any object in my object map.
    For example
    public static String SampleMethod(String passedString)
    String str = new String(passedString);
    ...do some more processing and sleeping
    return str;
    Let's say Object1 and Object2 make a call to SampleMethod. Object1 passes "Object1" and right before the Object1's SampleMethod returns str, Object2 makes a call passing "Object2". What would be the value of str for Object1's SampleMethodCall?
    Thanks :)

    If speaking about class members, then static members are stored in one place and are properties of the class, when non-staic members are stored in an object's memory and a properties of an object.
    However in your sample it's not the case.
    Local variables of a method are most likely allocated on registers or on stack (thus being rather properties of the call to a method).
    Thus in your case calls to SampleMethod done by Object1 and Object2 simultaneously (if you managed to do this in two different threads) will use different memory (most likely in threads' own stacks).
    As for calls to "new String" inside your method, the new string memory will be allocated dynamically each time the new operator is called, thus producing two different objects. The references to them will be stored in two local variables of two independent calls.
    Finally, Object1 will get a copy of "Object1" and Object2 will get a copy of "Object2", as expected.
    Vit

  • Enums with constant-specific method implementation

    Just faced the following problem. I have a persistent class with one of the fields of it is enum with constant-specific method implementation:
    @Persistent
    public class Message
       static public enum Type
           DEFAULT
               @Override
               public String getDescription() { return "Some description"; }
           public abstract String getDescription();
       private Type type;
    }When I try to store the record, I get the exception:
    java.lang.IllegalArgumentException: Class could not be loaded or is not persistent: messages.Message$Type$1The problem seem to be in that compiler creates a separate class, namely Message$Type$1.class for the DEFAULT instance and this class is not known by BDB..
    If I remove the constant-specific method from enum, everything's working fine (as the ..$1.class is not created by compiler).. Except the fact that I'd like to have constant-specific methods there..
    Any ideas on this? Maybe it's a bad idea to create constant-specific methods if it means that each constant would get own class file (and they would bloat the storage routines)?

    Hi Mikhail,
    I recreated the problem here and you're right, constant-specific methods aren't working. This isn't something we thought about, to be honest, or tested.
    Just based on an initial quick look I see that for the compiler generated class, the Class.isEnum method returns false, which is why we don't recognize this as an enum and eventually why we throw the exception you're seeing. But assuming that we can identify the class as an enum (that shouldn't be too difficult) I don't know what other problems we will run into in trying to support this.
    For now I think the best thing is to avoid using the constant-specific methods. I have opened a ticket (#18357) so that we'll remember to look into this in more detail and see whether it can be supported in the future.
    If we are able to support it, then I'm hoping that we won't to store extra metadata for constants that have methods. In other words, I'm hoping that we won't have to add any extra storage or processing overhead.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Why we should not declare a business method as final in EJBs - THX

    Why we should not declare a business method as final in EJBs - THX

    'cause it makes no sense at all and doesn't boost performance.
    regards
    dan
    scpj2

  • Declare deprecated a method

    Hello,
    I need to declare deprecated a method into my classes and simply I don't know how. I've tried to use a javadoc comment @deprecated but after I compile I don't receive the message that this method is deprecated.
    Thanx

    Check "What happens when an API is Deprecated"
    http://java.sun.com/products/jdk/1.1/docs/guide/misc/deprecation/deprecation.html
    and read the note, that says if you compile the class with the deprecated method along with classes that uses this method, then you won't get a warning. :)

  • Error - No defining declaration found for implementing declaration of partial method

    Hi,
    I am quite  new to c# and using lightswitch to create a webform. However, I have to write a code as per the webform logic and requirement and now getting error on this part -
    partial
    voidgridDeleteSelected_Execute(StringID)
    The error is -  No defining declaration found for implementing declaration of partial
    method
    Could someone please tell how this error can be resolved ? Please find the code attached below.
    Thanks.
    using System;
    using System.Linq;
    using System.IO;
    using System.IO.IsolatedStorage;
    using System.Collections.Generic;
    using Microsoft.LightSwitch;
    using Microsoft.LightSwitch.Framework.Client;
    using Microsoft.LightSwitch.Presentation;
    using Microsoft.LightSwitch.Presentation.Extensions;
    namespace LightSwitchApplication
    public partial class EditableServicesGrid
    partial void gridDeleteSelected_CanExecute(ref bool result)
    partial void gridDeleteSelected_Execute(String ID)
    if (!string.IsNullOrEmpty(ID))
    string sqldelete = "Update services set DELETED_FLG = 'Y' WHERE ID IN ( " + ID + ")";

    partial
    voidgridDeleteSelected_Execute(StringID)
    The error is -  No defining declaration found for implementing declaration of partial
    method
    Could someone please tell how this error can be resolved ? Please find the code attached below.
    Could you explanation what your requirement is? detailed information is necessary.

  • Why are enums with constant-specifics  methods no enums?

    I'm working on an application which uses reflection to determine how a certain object should be represented in the GUI.
    If an object is an enum it will be represented as a drop-down box.
    Yesterday however our code broke on a newly added enum which uses constant-specifics methods.
    To illustrate it I'm taking a code example from :
    http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
    public enum Operation {
    PLUS { double eval(double x, double y) { return x + y; } },
    MINUS { double eval(double x, double y) { return x - y; } },
    TIMES { double eval(double x, double y) { return x * y; } },
    DIVIDE { double eval(double x, double y) { return x / y; } };
    // Do arithmetic op represented by this constant
    abstract double eval(double x, double y);
    Now if you do Operation.PLUS.getClass().isEnum() to my surprise it returns false using 1.5.0_06.
    Is this a bug?

    Oh, looking at the source code would have been an option, yes ... sigh
    I see that there's a lot to learn when it comes to enums (at least for me). So based on what I believe to know about the matter, I'd say the issue was not overlooked. From a quick experiment, I saw that enum constants without constant-specific methods use an instance of their respective enum subclass as "representation", which in this case is not abstract (contrary to Operation, which is).
    So while from a logical point of view, enum constants with and without constant-specific methods should be considered equal(?), implementation-wise, they are not. I think the distinction between enums and enum constants is more of a Java language thing -- the JVM/bytecode is not really aware of it (much like inner classes) -- and is introduced by javac, using little "hacks" to implement the special abilities (which I'll definitely have to investigate when time permits).
    After all, isEnum() is invoked on the actual Class object representing the type of an instance. With reflection, you deal with the raw type, no support by javac magic. And indeed, Operation and Operation.PLUS are different types. Operation.PLUS exhibits different behaviour than Operation, and is missing some fields and methods (which could cause certain implications, I guess). Maybe one has to look at isEnum() more from an implementation perspective: isEnum() indicates that the respective class directly supports certain operations (i.e., is declared enum type in the Java source code), while Classes where isEnum() returns false do not. Yeah, the method name is a bit ambiguous, and intuition fools you here, as all the Classes, enums as well as enum constants, are subclasses of java.lang.Enum.
    PS: Enum.getDeclaringClass() deals with this issue, too.
    EDIT:
    Code wise it is not an elegant solution:
    - change my framework to check the modifiers iso.
    using isEnum
    or
    - implement the method using a switch statementClass theClass = anObject.getClass();
    if (anObject instanceof Enum) {
    if ( !theClass().isEnum())
    theClass = ((Enum) anObject).getDeclaringClass();
    (just a suggestion...)
    Message was edited by:
    oebert

  • Global Variable Declaration in ProcessRequest Method

    Hi All,
    i need to declare a variable(Global) in Process request Method and then i need to pass this variable value in ProcessRequest Method of Another Page.
    it is possible to declare a Global Variable in ProcessRequest Method.
    Process Request Method:
    if(pageContext.getSessionValue("varBatchID")!=null && pageContext.getSessionValue("varCustomerID")!=null)
    System.out.println("Second Else From Drill Down");
    String strCustID=pageContext.getSessionValue("varCustomerID").toString();
    String strBatchID=pageContext.getSessionValue("varBatchID").toString();
    System.out.println("CustomerID:"+strCustID);
    System.out.println("strngBatchID:"+strBatchID);
    Serializable[] parameters={strCustID,strBatchID};
    OAMessageStyledTextBean oamessagestyledtextbean=(OAMessageStyledTextBean)createWebBean(pageContext,"strCustID");
    oamessagestyledtextbean.setText(pageContext,"strCustID");
    pageContext.getApplicationModule(webBean).invokeMethod("backTocusttrxn",parameters);
    pageContext.removeSessionValue("varCustomerID");// Here i need to close this session Value and at the same time i need to pass this session value to another page PR Method. SO For that i need to Declare a variable(Global) and pass that variable value to another page.
    pageContext.removeSessionValue("varBatchID");
    Could you please any one give me the solution for this.
    Thanks,
    Mallik.

    Hi ,
    Create transaction variable and pass your value into that and get the same in other CO using below code,
    pageContext.putTransactionValue("IrcSelectedPersonId",value)
    pageContext.getTransactionValue("IrcSelectedPersonId");
    Regards,
    Vijay Reddy.

  • How do I declare a native method outside of the main class?

    Hi
    This is a JNI particular question.
    I am having a problem with generating the header .h file after executing javah. The file is generated correctly but is empty under certain circumstances.
    This is the 'empty file:
    =================
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class gui_GuiMain */
    #ifndef Includedgui_GuiMain
    #define Includedgui_GuiMain
    #ifdef __cplusplus
    extern "C" {
    #endif
    #ifdef __cplusplus
    #endif
    #endif
    This is what it should look like:
    =========================
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class gui_GuiMain */
    #ifndef Includedgui_GuiMain
    #define Includedgui_GuiMain
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class: gui_GuiMain
    * Method: getValueOIDTestMIB
    * Signature: ()V
    JNIEXPORT void JNICALL Java_gui_GuiMain_getValueOIDTestMIB
    (JNIEnv *, jobject);
    #ifdef __cplusplus
    #endif
    #endif
    The header file becomes "empty" when the native function getValueOIDTestMIB is declared in a different class than what my main() function is declared in.
    For example something like this will work:
    class Main
    public native void getValueOIDTestMIB
    static {
    System.loadLibrary("libsnmp++");
    //............some more functions etc.............
    public static void main(String[] args)
    //............some more stuff...........................
    But when I declare this:
    public native void getValueOIDTestMIB
    static {
    System.loadLibrary("libsnmp++");
    outside the class, in another class within the same package, nothing happens.
    I am probabily doing something stupid. Can somebody help or give me some guidance to where I should look. I come from a C++ background, not a guru in Java.
    Thanks

    You need to run javah and give it as a parameter the full class name of the class which contains the native methods.
    For example (if your class is called A and its package is a.b.c)
    javah -jni a.b.c.A

  • Passing any enum type to a method

    Consider I have created some enums:
    public enum Day {
        SUN, MON, TUE, WED, THU, FRI, SAT
    public enum Month {
        JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
    }I want to create a method that will accept any type of enum and display all values. So the call would look something like:
    showAll(Day);
    showAll(Month);I'm not sure what to pass to the method. My understanding of Generics is rudimentary at best, despite reading the tutorial several times now. Here is some uncompilable code that might illustrate:
    public void showAll(EnumType enumType)  // <--- not sure what to pass here
      Enum[] allValues = enumType.values();
      // then, loop over the allValues array and I can proceed from here
    }The actual code is needed is for displaying a list of checkboxes to the user where the input is the enum class, and the checkboxes are every enum value.

    brucechapman wrote:
    You could use this signature
    <T extends Enum<T>> void showall(Class<T> clazz); Then use reflection to invoke the values() method which you know is there because only Class objects for enums can be passed in.I'll be honest, that signature looks very strange to me. However, I tried it anyway and it worked even without reflection.
    public class PassingEnums
      public enum Day {
        SUN, MON, TUE, WED, THU, FRI, SAT
      public enum Month {
        JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
      public <T extends Enum<T>> void showAll(Class<T> clazz)
        T[] types = clazz.getEnumConstants();
        for (int i = 0; i < types.length; i++)
          System.out.println(types.toString());
    public static void main(String[] args)
    PassingEnums test = new PassingEnums();
    test.showAll(Day.class);
    System.out.println("---");
    test.showAll(Month.class);
    }Or were you thinking of something else?
    I guess I'll have to hit the tutorials again, since that signature looks foreign to me.
    Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Declared Web Dynpro method's javadoc not updating

    Hello all,
    I declared a method in a custom controller, and changed the Javadoc to something more meaningful than the usual "declared method.". Now I'm trying to call this method from another controller. That in itself works fine, but when using NWDS' auto-complete feature, I still see the old, initial Javadoc.
    I've tried building the project, reloading+rebuilding it, I even tried restarting the entire NWDS, all without success. Am I missing something? What does it take to get the NWDS to use the updated javadoc?
    Thanks in advance,
    Kars.

    Hi,
    if i am not wrong the JDK need to support the new java doc, mean to say are you using right jdk version for that. Coz javadoc.exe need to support.
    plz give a try to this setting:-
    Go to window-> preferences->jav->javadoc->javadoc command in that set the path for the javadoc.exe.
    Hope this may help you.
    Regards,
    Deepak

  • Wildcards in type declarations or only methods?

    Can you declare wildcards in type declarations such as:
    public class ListManager<List<?>> {
    }When I try this, I get the following compiler errror:
    C:\dev\hcj\tiger\src>c:\j2sdk1.5.0\bin\javac -source 1.5 oreilly/hcj/tiger/*.java
    oreilly/hcj/tiger/ListManager.java:21: > expected
    public class ListManager<List<?>> {
                                 ^
    oreilly/hcj/tiger/ListManager.java:31: '{' expected
    ^
    2 errorsWhat am I doing wrong [if anything]?
    TIA
    -- Kraythe

    public class ListManager<List<?>> {
    }When I try this, I get the following compiler errror:Hmm .. I was thinking about this. .. What i was trying to declare was a class that would use as a parameter any declaration of a List. So what I want is a class that will take List<Integer> and List<String> and so on. So the result would be to use it like this:
    public void someMehtod() {
        ListManager<List<String>> strListMger = ...
        ListManager<List<Integer>> strListMger = ...
    }So if not with the wildcard, how is this accoplished (if it can be accomplished at all).
    I would also like to do something like:
    public class ListManager<Type extends List<?>> {
    }In this manner I would at least have access to the type. Except the extends is a misnomer since i want type to be any List<> type.

  • Unable to declare Task T method in Interface

    I have a class Employee which inherits from abstract class
    MyAbstractClass<T>
    Employee : MyAbstractClass<Employee>, IEmployee
    There is a method on abstract class which operates on runtime type T supplied to abstract class :
    public async Task<T> AddSomething()
    T x = SomeAsyncMethod();
    return T ;
    The problem is how can I expose this method on IEmployee as the type T is decided at run time , I tried following but it did not work , please suggest
    public interface IEmployee
    // Task<Type> AddSomething();
    // Task <object> AddSomething();

    This is a duplicate of your
    previous post. Could you delete this question and update the other question if there was something missing?
    -Igor

  • Help with Declaring a Class with a Method and Instantiating an Object

    hello all i am having trouble understanding and completing a lab tutorial again!
    im supposed to compile an run this code then save work to understand how to declare aclass with a method an instantiate an object of the class with the following code
    // Program 1: GradeBook.java
    // Class declaration with one method.
    public class GradeBook
    // display a welcome message to the GradeBook user
    public void displayMessage()
    System.out.println( "Welcome to the Grade Book!" );
    } // end method displayMessage
    } // end class GradeBook
    // Program 2: GradeBookTest4.java
    // Create a GradeBook object and call its displayMessage method.
    public class GradeBookTest
    // main method begins program execution
    public static void main( String args[] )
    // create a GradeBook object and assign it to myGradeBook
    GradeBook myGradeBook = new GradeBook();
    // call myGradeBook's displayMessage method
    myGradeBook.displayMessage();
    } // end main
    } // end class GradeBookTest4
    i saved above code as shown to working directory filename GradeBookTest4.java
    C:\Program Files\Java\jdk1.6.0_11\bin but recieved error message
    C:\Program Files\Java\jdk1.6.0_11\bin>javac GradeBook4a.java GradeBookTest4.java
    GradeBookTest4.java:2: class, interface, or enum expected
    ^
    GradeBookTest4.java:27: reached end of file while parsing
    ^
    2 errors
    can someone tell me where the errors are because for class or interface expected message i found a solution which says 'class? or 'interface' expected is because there is a missing { somewhere much earlier in the code. i dont know what "java:51: reached end of file while parsing " means or what to do to fix ,any ideas a re appreciated                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Doesn't solve your problem, but this works for me...
    public class GradeBook
      public void displayMessage() {
        System.out.println( "Welcome to the Grade Book!" );
      public static void main( String args[] ) {
        try {
          GradeBook gradeBook = new GradeBook();
          gradeBook.displayMessage();
        } catch (Exception e) {
          e.printStackTrace();
    }

  • Error with declaring a method with array variable

    Hi,
    I had implemented this:
    import java.awt.*;
    import javax.swing.*;
    public class Oefening1
         public static void main(String args[])
              int array[]= new int[10];
              int getal;
              JTextArea outputArea = new JTextArea();
              Container container = getContentPane();
              container.add(outputArea);
              public void invoerRij(int array[10])
                   output +=" ";
                   for(int counter = 0; counter <10;counter++){
                        output +="Geef een getal in"+"\n"+array[counter]+"\n";
                        outputArea.setText(output);
    I had comilated this code while the compiler gave errors like these:
    A:\Oefening1.java:15: illegal start of expression
              public void invoerRij(int array[10])
    ^
    A:\Oefening1.java:24: ';' expected
    ^
    A:\Oefening1.java:12: cannot resolve symbol
    symbol : method getContentPane ()
    location: class Oefening1
              Container container = getContentPane();
    ^
    3 errors
    Tool completed with exit code 1
    Now i have read my book and finded out that the declaration of a method always starts with public.
    Can anyone halp me solving these probs? Thanks
    Crazydj1

    The problem is that you didn't close the previous method definition.
    Compiler error messages (in any language) often mistakenly report false errors on perfectly valid code immediately following the actual error.
    When you post code on these forums, please wrap in in &#91;code]&#91;/code] tags.

Maybe you are looking for

  • Swing Splashscreen

    Hi, I am a Java/Swing newbie, trying to convert from C++. I am writing a small app to interface with a PostgreSQL DB. I would like to include a splashscreen, and have used the code on sun's website (see below). I call this from the main(). The splash

  • Stuck with an error, need help.

    Hi Gurus, I am calling the workflow throught the function module SWW_wi_start_simple, I am throwing with an exception 'read_failed' Can any one say why this error being stated. Secondly, I coded as below to start the work flow with the wf container.

  • What is a STAR database

    Does anyone know what a STAR database is

  • Mouse Proble

    Hi guys, I now this is a Logic forum and I've also posted on the installation & setup forum, but this problem is affecting Logic, so I hope you guys can also help me. I'm having problems with my mouse (it's not bluetooth) 1.The secondry button is not

  • List Of Serious ISSUES after 2.0 download. NEED HELP!

    I just downloaded 2.0, as I wanted the havock I read about to settle before I changed over. I am having what I would consider Serious problems that I hope someone can assist with. I have the original 4Gig phone. 1. When I type an email or text messag