URL87
URL87

Reputation: 11022

Why does constructor with arg undefine the default constructor?

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 ?

Upvotes: 0

Views: 76

Answers (4)

Code-Apprentice
Code-Apprentice

Reputation: 83537

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.

Upvotes: 0

Chris Gerken
Chris Gerken

Reputation: 16392

It's the other way around.

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

Upvotes: 1

PermGenError
PermGenError

Reputation: 46428

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.

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240918

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

Upvotes: 2

Related Questions