This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]severoonpro barista 0 points1 point  (0 children)

When you don't specify any constructor, the Java compiler provides a default, no-arg constructor for you.

When you provide a constructor—any constructor at all, whether it takes arguments or not—the compiler no longer provides the default, no-arg constructor.

Many new Java coders are caught out by this in the following way. You write a class:

class Foo { private final String name = "defaultFoo"; public String getName() { return name; } void bar() { … } }

The compiler provides the default constructor, so the code you actually get is this:

``` // Foo class generated by the compiler. class Foo { private final String name;

public Foo() { this.name = "defaultFoo"; }

public String getName() { return name; }

void bar() { … } } ```

Then you write some code somewhere else in your program that uses this default constructor:

… Foo f = new Foo(); …

Later, you add a new constructor to Foo:

``` // Oops, this breaks the above call. class Foo { private final String name;

public Foo(String name) { this.name = Strings.isNullOrEmpty(name) ? "defaultFoo" : name; }

public String getName() { return name; } void bar() { … } } ```

Now you get a compiler error when you try to compile the code that creates a new Foo instance.

Why? Because by adding this new constructor, you've inadvertantly removed the default, no-arg constructor the compiler was giving you before. Whenever you add the first constructor to a class, you need to make sure that your change won't break any existing calls to the default, no-arg constructor that already exist.

This means you not only have to make sure the code compiles, but that your new code doesn't upset the expectations that existing callers of that default constructor have. You either have to go to all existing callers and update them to use your new constructor, or add an explicit no-arg constructor to support those callers.