File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Default Constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Default Constructor" Watch "Default Constructor" New topic
Author

Default Constructor

Ransika deSilva
Ranch Hand

Joined: Feb 18, 2003
Posts: 524
Hello World,
I just want to clarify this question.
Say if I am creating a class called User which has only one constructor which accepts
the user name, age, address etc as the parameters and this class has methods which returns the user name, user age etc. The question I am having is though there is no default constructor explicitly specified (I mean some thing like public User()) some on who is using this class can call the class bye using this kind of a syntax: User obj = new User();, but this object doesn't points to any user. So if that person calls obj.getUserName() what will happen?. If this is a problem what do I have to do in the creation of the class. Please explain this.
Thanks


SCJP 1.4, SCMAD 1.0<br />SCWCD, SCBCD (in progress)
Nathan Pruett
Bartender

Joined: Oct 18, 2000
Posts: 4121

If you do define a constructor for a class, you don't automatically get the default constructor, so this case doesn't come up exactly like your example. If you do put an empty default constructor in the class, and someone calls user.getUserName() on a class created through this default constructor, they would get whatever value was specified as default in whatever attribute really holds the name. This would be "null" if no default value was provided. You could set the default values either right where the attributes are defined, or in the default constructor if you want to provide actual default values.

Also, moving this thread to Java in General, as it doesn't cover GUIs or Graphics directly...


-Nate
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Ransika deSilva
Ranch Hand

Joined: Feb 18, 2003
Posts: 524
Ok Thanks I uderstood the concept.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Just to make the terminology clear:
The *default constructor* is the implicite constructor you get when you don't specify one.
If you do specify a constructor wich gets no arguments, official terminilogy is to *not* speak about a default constructor, but a *no-arg constructor*.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
Don't get me started about those stupid light bulbs.
 
subject: Default Constructor