• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Default Constructor

 
Ransika deSilva
Ranch Hand
Posts: 524
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Ransika deSilva
Ranch Hand
Posts: 524
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok Thanks I uderstood the concept.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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*.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic