问题
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