Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Java enumeration parameter passing
Java enumeration parameter passing
This is impossible because all instantiations of objects in Java are in the heap. If ordinary class instance variables, such as those defined in method 1, are passed to method 2, since the instance variables in method 1 and method 2 correspond to the same object instance in the heap, the value of the object instance is modified in method 2, and the value in method 1 will also be changed. But enumerations in java are not like this. For example, the following code:

Public? Class? EnumClass? {

Public? Static electricity Invalid? Main (string? []? args){

Color? Color? =? Color. Red;

Transform (color);

system . out . println(color . name());

}

Public? Static electricity Invalid? Conversion (color? c){

system . out . println(c . name());

c? =? Color. Blue;

}

}

enum? Color {

Red, blue and green;

As mentioned in your question, both outputs are red. For specific reasons, we can decompile this class with javap. Get the following code

Compilation? From where? " EnumClass.java "

Final? Class? org.concurrency.art.Color? Extension? Java . lang . enum & lt; org . concurrency . art . color & gt; ? {

Public? Static electricity Final? org.concurrency.art.Color? Red;

Public? Static electricity Final? org.concurrency.art.Color? Blue;

Public? Static electricity Final? org.concurrency.art.Color? Green;

Public? Static electricity org.concurrency.art.Color[]? values();

Public? Static electricity org.concurrency.art.Color? value of(Java . lang . string);

Static electricity {};

You can see that enumeration is actually implemented with class. The value of the enumeration is a constant of the static final type of the class. When the EnumClass class is loaded, the virtual machine will create these three instantiated variables in the heap area. This can answer why the change is invalid. When the main method passes the Color variable to the c of the convert method, both of them point to the same address in the heap area, where the color is located. Found red instance. Then the variable c is redistributed, and the variable c points to the position of the color. Blue instance in the heap area. This assignment has nothing to do with the color variable in the main method, and the color variable in main is still color. Red instance point. So the color variables in the main method have not changed after the covert method is executed.

If you want it to change, I think there are two ways. One way is for the Cover method to return a required enumeration variable and assign it to color in main. Another way is to encapsulate this variable with another class and pass it to the Cover method. I hope it helps you.