It's not a secret anymore!*
The moose likes Java in General and the fly likes Default Constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Default Constructor" Watch "Default Constructor" New topic
Author

Default Constructor

Patrick Day
Greenhorn

Joined: Jul 23, 2011
Posts: 8

I wondering if someone could explain this concept to me. "A no-argument Constructor is not necessarily the default Constructor, although the default Constructor is always a no-argument Constructor". This completely confused me, I hope someone can explain this in layman terms.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18494
    
  40

A no-arg constructor is a constructor that takes no arguments. A default constructor is a constructor that the java compiler creates for you when you don't define any constructors in your class definition.

If you define a constructor in your class, then no default constructor will be created for you. And if your constructor takes no arguments, then your constructor (which is not a default constructor) is a no-arg constructor.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37879
    
  22
Try this:You think those two classes do the same thing, and you would be right. And if you compile them, and then inspect the bytecode, like this:... you will see the no-args constructor, with and without its contents. I think it will say something like <init> against it.
Now repeat the procedure with the Baa class. You can see that the compiler has added a constructor, which is a default constructor, doing the absolute minimum possible for a constructor, ie calling the superclass' constructor.
The Java™ Language specification tells you about default constructors, but it isn't easy to read.
Patrick Day
Greenhorn

Joined: Jul 23, 2011
Posts: 8

Thank you both Henry & Campbell, I understand it now
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37879
    
  22
You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Default Constructor
 
Similar Threads
anonymous inner class
why compile error
Jargon
Inner Class concept
Inner Class concept