0

Why does the default parameter-free constructor fail, when a parameter-constructor is given in Java?

What's the point of this design?

For example:

class Father {
    public String name = "Father";

    public Father(String name) {
        this.name = name;
    }
}

public class Test {
    public static void main(String[] args) {
        Father p = new Father();  //Error
    }
}
StackUser
  • 21
  • 1
  • `Father()` does not exist, because you specifically defined your own. Either remove that, or create the no-arg constructor yourself. – Abhijit Sarkar Aug 11 '20 at 03:18
  • It doesn't 'fail'. It is not *generated* by the compiler, in accordance with [JLS #8.8.9](https://docs.oracle.com/javase/specs/jls/se14/html/jls-8.html#jls-8.8.9). – user207421 Aug 11 '20 at 03:39
  • You've defined a constructor thus the default constructor is not generated by the compiler. Nor would you want it to be generated as that could allow your class to be instantiated with illegal state. If you need a no-argument constructor alongside other constructors then you need to declare them all. – Slaw Aug 11 '20 at 03:41
  • Answer: Because the language is defined to work that way. Related: https://stackoverflow.com/questions/11792207 – Bohemian Aug 11 '20 at 03:50

1 Answers1

1

If you supply no constructor, the compiler will generate a default, zero-argument constructor.

If you supply any constructors, the compiler will not generate any others. In this case, the single-argument constructor is supplied by you, so the compiler does not generate a default constructor.

EJK
  • 12,332
  • 3
  • 38
  • 55
  • I know what you mean. But what I really want to know is that when I defined a constructor of my own, why the compiler will not generate a parameterless? And If a parameterless constructor is created in that case, what is the negative impact on the project? – StackUser Aug 11 '20 at 06:27
  • 1
    @StackUser The negative impact is loss of control. If you've declared one or more constructors then those are the constructors of the class. To have the compiler continue to generate a default constructor means there's now an additional constructor which you did not code for. How can the compiler possibly know how to implement the default constructor in a way that satisfies your class' contract? Answer: It can't. Likely the only reason a default constructor is generated when none were explicitly declared is because the Java language requires every class to have at least one constructor. – Slaw Aug 11 '20 at 09:53
  • @Slaw Well put. You should enter that as an answer as it best addresses what the OP was really asking about. – EJK Aug 11 '20 at 16:17