Calling super()

后端 未结 12 1067
孤独总比滥情好
孤独总比滥情好 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:50

    If you provide a class like this:

    public class Foo
    {
    }
    

    or this:

    public class Foo()
    {
        public Foo()
        {
        }
    }
    

    the compiler will generate code for this:

    public class Foo()
    {
        public Foo()
        {
            super();
        }
    }
    

    So, strictly speaking, the call to "super()" is always there.

    In practice you should only call "super(...)" where there are parameters you want to pass to the parent constructor.

    It isn't wrong to call "super()" (with no parameters) but people will laugh at you :-)

提交回复
热议问题