Calling super()

后端 未结 12 1088
孤独总比滥情好
孤独总比滥情好 2020-12-01 12:24

When do you call super() in Java? I see it in some constructors of the derived class, but isn\'t the constructors for each of the parent class called automatically? Why woul

12条回答
  •  余生分开走
    2020-12-01 12:46

    Although super() does nothing functionally for the compiler (the superclass default constructor is called automatically), it certainly does a lot for me. It says to me: "Do not remove the empty constructor. It's there for a reason".

    A perfect example is where you create Spring managed beans or JPA Entities and you've created a parameterized constructor.

    @Entity
    public class Portfolio {
    
        ...
    
        public Portfolio() {
            super(); // This says to me: DON'T DELETE!
        }
    
        /**
        *  Because there is now a parameterised constructor (me), 
        *  the default constructor no longer exists. This means
        *  that for this example, you need an empty constructor in place (above) 
        **/
        public Portfolio(String name) {
            this.name = name;
        }
    }
    

提交回复
热议问题