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开发者_如何学C 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..
If "state" is static, then yes. Otherwise no.
Change to:
private static State state;
This makes state
shared among all instances of your class.
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.
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.
精彩评论