Hi, i have got some doubts on "transient". Please answer the following questions: 1) Are following variable declarations valid: (a) transient static int i=0; (b) transient final int j=0; (c) transient static final int k=0; Roberts-Heller-Ernest states on page 90 that "transient variables may not be static or final". I have compiled the code including the above declarations and there was no error. 2) Can transient variables be instance variables? I have tried to compile the above declarations as instance variables but reported an error "Interface or class required" 3) Do i need to implement Serializable or Externalizable on the class in which i am declaring transient variables? I have tried to compile with out implementing any of the two interfaces and I do get compiler errors/ Why am i getting these errors???
Hi Sagar, * The class need not be Serializable or Externalizable to declare itz fields as "transient" [ though itz meaningless to do so ] * But to write the instance of the class ( serialize) into a stream, the class need to implement Serializable or Externalizable, else "NotSerializableException" will be thrown. This link shown some codes http://www.javaranch.com/ubb/Forum24/HTML/004691.html
Hi, Regarding your questions, 1) RHE are wrong here . Transient variable can be both static and final. It is also listed in the errata.Please check it from there. 2) For your second question ,please see the following link- http://www.javaranch.com/ubb/Forum24/HTML/001550.html 3) About your third one,I don't think you HAVE to implement either of the interfaces . I am not really sure about this so please correct me if I am wrong. Ira
Hi, Sagar 1)I found nothing in the JLS mentioning the restrictions that you wrote. And you are right, I compiled it too and it works. 2) The whole point of declaring a member variable transient is to avoid the automatic serialization of instance members that would otherwise happen. It is pointless to declare a member variable as static because static "members" won't get serialized. And it is pointless to declare member variables that are constants (static final). 3) You do need to implement Serializable (or Externalizable) on a class that you will be serializing instances (of the class). Here is some code, stored in TransientTest2.java
------------------ Hope this helps. Have a good day.