Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object instance without new?

As we know we can instantiate an object without new keyword by using classloader/object cloning/object serialization. When I am using these techniques to create an object, is the constructor called or not?

like image 988
JavaUser Avatar asked Aug 05 '26 02:08

JavaUser


2 Answers

For Object.clone no constructor is called.

For serialisation, the most derived non-serialisable base-class no-arg constructor is called. Typically implemented by loading bytecode that does not validate. The constructor must be accessible to the base-most serialisable class.

like image 60
Tom Hawtin - tackline Avatar answered Aug 06 '26 17:08

Tom Hawtin - tackline


As far as I know all the three use the constructor even serialization.

http://java.sun.com/j2se/1.4.2/docs/api/java/io/Serializable.html

The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case

like image 38
Xavier Combelle Avatar answered Aug 06 '26 17:08

Xavier Combelle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!