Overriding default constructor in Java

余生颓废 提交于 2020-01-14 15:32:07

问题


Pretty easy question, but anyway: is there any reason to override default constructor like this:

public SomeObject(){
}

It is public. It is does not have any logic. So, is there necessary? I didn't see the whole picture?

Appreciate all your help.


回答1:


One reason to define an empty no-arg constructor is if there is also a non-default constructor and the no-arg constructor is still desired to be accessible (public or protected).

This is because any [other] constructor definition will prevent the automatic addition of the default no-arg constructor:

The compiler automatically provides a [public] no-argument, default constructor for any class without constructors.

(See the next bit in that link as well, where it talks about the default super constructor that will be called.)

Even if the no-arg constructor is never used manually, it can be important for other things, e.g. Serializable:

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.




回答2:


Only reason may be, sometimes you may have constructor with parameters and you want to allow object creation without passing parameters (by invoking default constructor).

When you have constructor defined, no arg constructor won't be available, so you have to explicitly add it to your class.




回答3:


Unless you have any initialization logic there is no need for overriding the default constructor.




回答4:


The exact reason is, if you don't, you will have problem while extending classes

class A{
    int a;
    public A(int a){
        this.a=a;
    }
    // public A()
    //{
        // here super(); will be called again, calling Object class's constructor thus initializing any uninitialized variables
    //}
}

class B extends A{
    int b;
    public B(int b){
        // here automatically, "super();" will be executed. if it is not present, error!
        this.b=b;
    }
}

go through this and this to understand what I was trying to say.

EDIT: some of the answers are actually wrong because as you can see, defining the parent no-arg constructor is mandatory while extending classes unless you will explicitly call overloaded super constructor with args.



来源:https://stackoverflow.com/questions/11849942/overriding-default-constructor-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!