mre
mre

Reputation: 44250

Are enum values shared among all instances of a class?

So, say I have the following enum declaration:

public class WatchService implements Runnable
{
    private State state;

    private enum State
    {
        FINDING_MANIFEST, FINDING_FILES, SENDING_FILES, WAITING_TO_FINISH
    };
    // other stuff
}

Now, say I have the following abstract class:

public abstract class MyOtherAbstractClass extends MyAbstractClass
{
    // other stuff
    private WatchService watchService;
    // other stuff
}

Now, say I have the following class that extends the aforementioned abstract class:

public class MyClass extends MyOtherAbstractClass
{
    // other stuff
}

If I have several instances of MyClass, will they all share the current State value? For instance, if one instance declares state = State.FINDING_MANIFEST;, will all instances have the current state of FINDING_MANIFEST?

I hope this makes sense..

Upvotes: 0

Views: 388

Answers (3)

f1sh
f1sh

Reputation: 11943

If I understand the question correctly, this isn't specific to enums. Imagine the same situation using a private String state = "FINDING_MANIFEST";. Unless state is static, it won't be shared among instances.

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76908

No. state is a instance variable. Each instantiated object has its own.

If you defined it as

private static State state;

Then there would only be a single instance of it, and all instances of the class would see the same one.

Upvotes: 1

Erik
Erik

Reputation: 91300

If "state" is static, then yes. Otherwise no.

Change to:

private static State state;

This makes state shared among all instances of your class.

Upvotes: 4

Related Questions