枚举类型不能像java中的对象引用一样传递给函数吗?

时间:2013-07-31 23:23:24

标签: java

object a = new object(); 
method(object a);

如果我在此方法中更改a的值,则还应更改此方法外部的值。但是

enum b = enum.something; 
method(enum b);

如果我在这个方法中改变b的值,在这个方法之外的b的值,我发现它没有改变。我不知道为什么?

3 个答案:

答案 0 :(得分:1)

enum不是类型,enum是声明性关键字。此外,参数类型不是在方法调用中声明,而是在方法声明中声明。这样会更正确:

public class Main {

    public enum Suit { CLUBS, SPADES, HEARTS, DIAMONDS }

    public static void main(String[] args) {
        Suit suit = Suit.CLUBS;
        print(suit);
    }

    public static void print(Suit suit) {
        System.out.println(suit);
    }
}

答案 1 :(得分:0)

Object a = new Object(); 
method(a);
public void method(Object a){
        // do operation on Object a 
}

由于您传递了对象引用,因此更改将反映在您的实际对象上。

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

Because they are constants, the names of an enum type's fields are in uppercase letters.

枚举是常量,意在保持其状态。就像public static final常量一样。

答案 2 :(得分:0)

不确定你在做什么或问什么,但这就是我所知道的与您的问题相关的内容:

MyObject aOutside = new MyObject(); // 
method(MyObject a) {
  a.setSomeValue("value"); // Change the object referenced by aOutside
  a = new MyObject(); // Does *NOT* change aOutside
}

enum MyEnum { AAA, BBB; }
MyEnum  bOutside = MyEnum.something; 
method(MyEnum b) {
  b = MyEnum.AAA; // Does *NOT* change bOutside
}