Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (4k points)

In C#, C++ and Java, when you create a constructor taking parameters, the default parameterless one goes away. I have always just accepted this fact, but now I've started wondering why.

What is the reason for this behavior? Is it just a "safety measure/guess" saying "If you've created a constructor of your own, you probably don't want this implicit one hanging around"? Or does it have a technical reason that makes it impossible for the compiler to add one once you have created a constructor yourself?

1 Answer

0 votes
by (46k points)

There's no reason that the compiler couldn't add the constructor if you've added your own - the compiler could do pretty much whatever it wants! However, you have to look at what makes most sense:

  • If I haven't defined any constructor for a non-static class, I most likely want to be able to instantiate that class. In order to allow that, the compiler must add a parameterless constructor, which will have no effect but to allow instantiation. This means that I don't have to include an empty constructor in my code just to make it work.
  • If I've defined a constructor of my own, especially one with parameters, then I most likely have logic of my own that must be executed on creating the class. If the compiler were to create an empty, parameterless constructor in this case, it would allow someone to skip the logic that I had written, which might lead to my code breaking in all number of ways. If I want a default empty constructor in this case, I need to say so explicitly.

So, in each case, you can see that the behaviour of current compilers makes the most sense in terms of preserving the likely intent of the code.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.5k answers


108k users

Browse Categories