Why does constructor with arg undefine the default constructor?

痞子三分冷 提交于 2019-12-12 03:46:49

问题


Consider -

public class Class_A {

    public void func() {...}

    public void func(int a){...}

All three -

Class_A a = new Class_A(); // legal
a.func(); // legal
a.func(1); // legal

But After constructor with arg like public Class_A (int a){...} is added to Class_A , the default constructor become to be -

Class_A a = new Class_A(); // The constructor Class_A() is undefined

Thats force me to add public Class_A() {/*Do Nothing*/} into Class_A .

Since each class has default constructor , why doesn't both default constructor and constructor with arg can exist together just same func() and func(int a) are ?


回答1:


it has default constructor unless you define your own constructor, in this case you need to re define default constructor




回答2:


Because If you write a constructor, compiler wouldn't write a default constructor for you. you have to write one explicitly.

From JLS:

If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.




回答3:


It's the other way around.

If you don't have any constructor you get the no-arg one by default.




回答4:


The name "default constructor" implies that it is provided when you don't provide one yourself. As soon as you provide your own constructor, the compiler will not generate a default constructor for you.

Be careful not to confuse the default constructor with the no-arg constructor. These are two entirely different things.



来源:https://stackoverflow.com/questions/13982345/why-does-constructor-with-arg-undefine-the-default-constructor

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