Announcement Announcement Module
Collapse
No announcement yet.
Parent Constructor called when instantiating child class Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Parent Constructor called when instantiating child class

    I noticed that when instantiating a bean using the ApplicationContext.getBean(beanId) method, the constructor of the superclass gets called even though I am instantiating a bean of the subclass.

    For example, if I have the following setup:

    HTML Code:
    public abstract class BaseHibernateDao {
      public BaseHibernateDao() {
        System.out.println("parent constructor");
      }
    }
    public class UserHibernateDao extends BaseHibernateDao {
      public UserHibernateDao() {
        System.out.println("child constructor");
      }
    }
    and in the applicationContext.xml I have the following:

    HTML Code:
      <bean
          id="userHibernateDao "
          class="com.mycompany.UserHibernateDao"
          singleton="false"
      />
    and I instantiate the bean programmatically:

    HTML Code:
    ApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    UserHibernateDao  userDao =  (UserHibernateDao) springContext.getBean("userHibernateDao");
    the output will be:

    HTML Code:
    parent constructor
    child constructor
    which is not what I want since I only want the child constructor invoked unless I explicitly called super() which I'm not doing.

    Following is part of the stacktrace that told me who is responsible for bean instantiation:

    HTML Code:
    at java.lang.reflect.Constructor.newInstance(Constructor.java:494)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:172)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)

    Any idea on how to avoid the parent construcor getting called?

  • #2
    Java 101

    super() is implicitly invoked in subclasses if the parent class has a zero-argument constructor.

    If the parent class has no zero-argument constructor, the subclass must invoke super(...) in the first line of the constructor explicitly. Otherwise, there is compilation error.

    Parent constructor is always called. Otherwise, how can a subclass inherit the fields and behaviours of the superclass?

    Comment


    • #3
      Originally posted by seabludude
      super() is implicitly invoked in subclasses if the parent class has a zero-argument constructor.

      If the parent class has no zero-argument constructor, the subclass must invoke super(...) in the first line of the constructor explicitly. Otherwise, there is compilation error.

      Parent constructor is always called. Otherwise, how can a subclass inherit the fields and behaviours of the superclass?
      Thanks. Brain Fart.

      Comment

      Working...
      X