Almost all Java developers knows that compiler adds a default constructor or better known as no argument constructor in every Java class, but many of them forget that, it only does when you don't provide any other constructor. Which means it becomes developers responsibility to add a no argument constructor, if he is adding explicit constructor. Now, Why it's important to provide default constructor in Java, What happens if your class don't have a no argument constructor? Well, this is how it's asked in many Java interviews, most commonly as part of Spring and Hibernate interviews. It's not mandatory to define default constructor, but if you are writing Hibernate persistent class, JPA entities or using Spring framework to manage object creation and wiring dependencies, you need to be bit careful. Many of open source framework, uses reflection to create instance or Object at runtime, based upon name of class. For example When Hibernate creates instance of entities using reflection it uses Class.newInstance() method, which require a no argument constructor to create an instance. It's effectively equivalent of new Entity(). This method throws InstantiationException if it doesn't found any no argument constructor in Entity class, and that's why it's advised to provide a no argument constructor.
Read more »
Langganan:
Posting Komentar (Atom)
0 komentar:
Posting Komentar