private memebers of a class should never be accessible from outside the class. But how do the private methods of Book? Here's the full source code. ObjectInputStream / ObjectOutputStream is intercepting the private methods of Book. Do I call this violation of encapsulation?
import java.io.*;
class ReadingMaterial { protected String author; protected String subject; protected int yearwritten; public ReadingMaterial() {}
System.out.println(); System.out.println("Printing original book..."); System.out.println(bookorg); System.out.println("Printing new book... "); System.out.println(booknew); System.out.println("The original and new should be the same!"); System.out.println(); } }
"Twenty years from now you will be more disappointed by the things that you didn't do than by the ones you did. So throw off the bowlines. Sail away from the safe harbor. Catch the trade winds in your sails. Explore. Dream. Discover." - Mark Twain
Jeroen T Wenting
Ranch Hand
Joined: Apr 21, 2006
Posts: 1847
posted
0
no you don't
While you can cause encapsulation to become broken by serialisation and reflection you're when you do that on your own. You're already breaking the design contract of the class as a user of that class, which means you're yourself in violation of the trust between the API developer and yourself.
42
Nishant Verma
Ranch Hand
Joined: Jun 14, 2006
Posts: 41
posted
0
Jeroen Thanks !! API has intercepted the private methods. That was my concern. Your answer helped me a lot. Sun recommends this for serialization - sensitive classes should never be serialized or the sensitive fields should be declared transient. Otherwise any other class can use the ObjectInputStream to read the sensitive fields.