4

I was going through the basics of Java IO and I saw that, in order to use a custom writeObject function in a class, it has to be declared private.

private void writeObject(ObjectOutputStream oos);

Then, when we call

oos.writeObject(myClassObject);

This function looks for the private writeObject method in MyClass and executes it.

My Question is: If this is true, then won't it be a violation of Data Abstraction concept when a function can call the private method of another class? What is the reason for this feature?

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
  • The question (the title) is a bit misleading. You are not asking the *how*, but the *why*. – meskobalazs Jul 16 '15 at 09:29
  • possible duplicate of [Why are readObject and writeObject private, and why would I write transient variables explicitly?](http://stackoverflow.com/questions/7467313/why-are-readobject-and-writeobject-private-and-why-would-i-write-transient-vari) – RealSkeptic Jul 16 '15 at 09:41

2 Answers2

0

I am mostly doing an educated guess here.

The way, how serialization works is logically tied to a single object class. It does not really make sense to inherit it, so it is forced to be private.

It really violates some OO principles, but I can see reason in this approach. Especially because serialization is already heavily depending on reflection.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63
0

Yes, it violates OO principles, as indeed does the serialization process in general (take for example its ability to construct object instances without an apparent invocation of a constructor).

As for the how, it's done using a combination of internal trickery and the Reflection API.

biziclop
  • 48,926
  • 12
  • 77
  • 104