Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

default constructor confusion

 
Alangudi Balaji Navaneethan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic