2

I have been searching web to find the answers of some of the queries related to enum class in java.

I was curious to know internals of enum class hence i open the source code and found some methods there that are as below --

protected final void finalize() { }

I found finalize method there which is a blank implementation , and not properly commented. So my query is why an enum class cannot have finalize method means is there any harm to have finalize method in enum class or is there any other reason behind this.

I am more confused after seeing this class. Any help will be appreciated. Thanks in advance.

user207421
  • 305,947
  • 44
  • 307
  • 483
rraghuva
  • 131
  • 1
  • 10
  • It is better to split these into 2 questions. What will you do if one answer answers only one of the questions and another answers the other question? – user1803551 Jan 04 '16 at 08:30
  • Ok i will break this into two questions. – rraghuva Jan 04 '16 at 08:31
  • 2
    Possible duplicate of [Does Garbage Collector run on Enum type?](http://stackoverflow.com/questions/23525768/does-garbage-collector-run-on-enum-type) – user1803551 Jan 04 '16 at 08:59
  • "Default serialization is prevented" is untrue, and you've provided no evidence to the contrary. – user207421 Jan 04 '16 at 09:17
  • @EJP i have updated the question due to this the query related to serialization is asked in another question . Please find it @ [why-default-serialization-is-prevented-in-enum-class] (http://stackoverflow.com/questions/34589325/why-default-serialization-is-prevented-in-enum-class) – rraghuva Jan 04 '16 at 10:47

2 Answers2

0

Enum class have only 1 instance per enum value decalred across a single instalce of JVM. They are essentially singletons on the JVM.

It's easy to prove this on Oracle JVM since the default identity hash code of object is the memory address. Then you can see anywhere in your program when you set up an Enum instance, it's actually the same object.

Alex Suo
  • 2,977
  • 1
  • 14
  • 22
-2

1)- enum is used for declaring constants, enum constatnts static, ie class level...hence can not be serailized.

2)-all the object class methods except toString() are overrided and declared as final in Enum class so the end user cannot modify any of the constants.

  • 1
    Hi Shobhit, Thanks for reply... But i can see enum class is implementing serializable interface also . Please check the signature. public abstract class Enum> implements Comparable, Serializable – rraghuva Jan 04 '16 at 08:28
  • Did you try to serialize an `enum`? Did you get an exception? – user1803551 Jan 04 '16 at 08:29
  • Enums *can* be serialized, if they implement `Serializable`, and there is a [lot of wording in the Object Serialization Specification to support it](http://docs.oracle.com/javase/7/docs/platform/serialization/spec/serial-arch.html#6469). – user207421 Jan 04 '16 at 09:52