Why do we need to declare default constructors in Java classes?
-
Consider this. Fact: In Java, every variable has a default value. If we don't initialize a variable when it is first created, Java provides a default value to that variable automatically. int has default value as zero. So why would we need to put a default constructor if the value is to be initialized to zero? [code] class X { int y; X (int a) { y=a; } X () { //default constructor not really needed here, is it? y=0; } } [/code]
-
Answer:
Constructors establish the object's state. From this example, it may appear that the only purpose of the constructor is to set a variable's default value, which will be 0 anyway. This default constructor will be implicitly declared and created by the compiler if no overloaded constructors are used - but here, the constructor X(int a). From the specification: http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8.9 The spec doesn't say why the default constructor will not be implicitly created if overloaded constructors are used. I think it makes sense that, if the programmer creates overloaded constructors, they waived the convenience that the compiler will create the default constructor.
Miguel Paraz at Quora Visit the source
Other answers
You are right when you say that every primitive data-type has a default value assigned to it and hence, there seems no legitimate need to create a default constructor. Sometimes, this seems like a legacy issue that the Java creators carried over from C++. However, there are a few things that happens when you don't create a default constructor. If you only have a non-default constructor in your class that assigns non-default values to the instance variables, you won't be able to create a default object because the program won't be able to find the required constructor. This would violate the function overloading rule of OOD. Also, you need a default constructor while creating a javabean. This is because you need to ensure that the user of the bean gets as much latitude (in defining the variables) as possible. This is usually achieved through accessor methods. When you have accessor methods, I think that it'll be superfluous for us to put in a non-default constructor.
Kunal Suri
1. if you have no constructors at all, the X(){super();} will be added automatically. I'd still recommend you to add it, for clarity, and personally I always explicitly call the super() but that's a bad habit because of a bad experience in the past caused by some bug on the Eclipse compilation (compiling via maven worked, via Eclipse I had weird behaviour). I prefer clarity over simplicity, so I always add those X() and supers and always auto-box manually. In other words, my Eclipse has all warnings enabled (except NLS). 2. if you add at least one constructor, the no-args constructor will not be added automatically. If you remove the X(), you can only create the object via X(int), never X(). Hence again why clarity and "redundant" code is better. 3. in Java all class instances are automatically initialised and cleared out. that "y" will always be 0. Even an byte[] b = new byte[100] will be ensured to be 100 zeros. On the other hand, variables inside a scope do need to be initialised, for example: public void foo() { int x; System.out.println(x); // doesn't compile because x is not initialised } 4. your code makes sense in two cases - assume that int y is a final value that you want to initialise on construction and ensure it never changes again (great for high performance). In that case you'll need to explicitly use the two constructors, as the "final int y" will only compile if all constructors initialise the "y" with some value.
Bruno D. Rodrigues
I'm confused by your question. You have no need in declaring default constructors. The sample code will work fine without "X()". The only difference will be that you will not be able to instantiate X without parameters.
Mantas Balnys
Compilation Error-Implicit super constructor X() is undefined. Must explicitly invoke another constructor. So when you have written parametrised constructor in super class X,then no default constructor will be inserted there implicitly. But according to constructor chaining rule,constructor is invoked in subclass to super class order but execution of constructors is done in super class to subclass order . So for maintaining the constructor chaining rule,in each subclass constructor if you have not written the call to default constructor of super class i:e "super()" as a first statement explicitly then automatically "super()" is implicitly written there as a first statement,so if no default constructor corresponding to "super()" will be there in the super class,compilation error will be there. you just remove the comment,you will see that compilation error will be removed. So finally one can conclude that for maintaining the constructor chaining rule,it is a good practice to write the default constructor in your class,so that if in future you are going to extend that class no extra maintenance will be needed for validating the constructor chaining rule.
Dhiraj Chandra Drj
At the beginning of an object's life, the Java virtual machine (JVM) allocates memory on the heap to accommodate the object's instance variables. When that memory is first allocated, however, the data it contains is unpredictable. If the memory were used as is, the behavior of the object would also be unpredictable. To guard against such a scenario, Java makes certain that memory is initialized, at least to predictable default values before it is used by any code. Source - http://www.buggybread.com/2014/05/java-interview-questions-and-answers-on_4133.html
Vivek Vermani
No one declares the default constructor in to java program. Compiler itself creates a default constructor if no other constructor present in our class. That constructor invokes the super class constructor automatically.
(Vishwak) Vijay Ranha
Related Q & A:
- How do you measure national income? and why do countries need to measure it?Best solution by en.wikipedia.org
- I need help with writing up the Java Code.Best solution by Yahoo! Answers
- Why do we need to sleep?Best solution by Yahoo! Answers
- Why do you need to enter your billing address on amazon.com?Best solution by Yahoo! Answers
- Why can't I change my default picture?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.