Why does constructor with arg undefine the default

2019-08-23 02:43发布

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 ?

4条回答
一纸荒年 Trace。
2楼-- · 2019-08-23 03:08

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.

查看更多
再贱就再见
3楼-- · 2019-08-23 03:09

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.

查看更多
倾城 Initia
4楼-- · 2019-08-23 03:17

It's the other way around.

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

查看更多
够拽才男人
5楼-- · 2019-08-23 03:33

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

查看更多
登录 后发表回答