Reputation: 7844
I found this code online where the person is instantiating a class which has a private constructor outside the class. I am not able to understand how this works, cause from what I had read earlier, you use a private constructor in a class so that it cannot be instantiated outside the class.
public final class A extends B {
private A(Something, Something)
{
//Something
}
public void someMethods()
{
//Something
}
}
public final class B {
private A a;
public void someMethod()
{
final ObjectInputStream objectInputStream = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
a = (A) objectInputStream.readObject();
objectInputStream.close();
a.someMethods();
}
}
I just want to understand what exactly is going on here? I tried reading up on ObjectInputStream
but could not get anything out of it.
Upvotes: 2
Views: 124
Reputation: 16392
Looks like the code is instantiating an object via serialization and then casting that object to class A. Nowhere in here is the class A constructor invoked.
Upvotes: 5
Reputation: 88707
Well, the constructor is never called since the object is not being constructed but deserialized. Thus the access modifier has no effect here.
Serialization is basically the process of writing part of the content of the heap into some stream/file etc. Constructing an object will create a new object on the heap and call the constructor to initialize it. It then has a state which is retained during serialization. Hence there's no need for initializing that object again when it is deserialized. It's just like reading that part of the heap from a stream/file into memory again.
Besides that, keep in mind that there are ways to circumvent access modifiers by using reflection.
Upvotes: 2
Reputation: 120858
This has to do with Serialization and when you de-serialize, the Constructor is actually NOT called.
Upvotes: 1