wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes default constructor confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "default constructor confusion" Watch "default constructor confusion" New topic
Author

default constructor confusion

Alangudi Balaji Navaneethan
Ranch Hand

Joined: Apr 28, 2004
Posts: 42
I studied in Head First Java that,

We need to provide a constructor with arguments to instantiate a class with initial values. If we do not provide any constructor one will be arranged by jvm.

I also read in a book that, if we give constructors with arguments then we must also give constructors without arguments also...

But when I tried the following program I am puzzled with the results what is the problem



I expected a compile time error. But it compiled and gave 100 as result.


if you think you can you r right<br />if you think you can not you r double right
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi cowboys,


Alangudi Balaji Navaneethan wrote:

I also read in a book that, if we give constructors with arguments then we must also give constructors without arguments also...


No, that's wrong. You don't have to put a no-arg constructor in, as your example shows.

Only in cases of inheritance, where a subclass might call your superclass' no-arg constructor, and you have only constructors with args, you would had to add one.
Example, if I extend your class:


Then the compiler automatically adds the following lines (in italics):

...and then TestChild will not compile, because you out-commented the no-arg constructor in Test. And TestChild (automatically) calls it.



Yours,
Bu.


all events occur in real time
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: default constructor confusion
 
Similar Threads
Inheritance Question
Constructor Problem
Constructors
Constructor
constuctor concept