• Post Reply Bookmark Topic Watch Topic
  • New Topic

Default constructor  RSS feed

 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


This class has not constructor.
Default constructor. If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans).

http://leepoint.net/notes-java/oop/constructors/constructor.html
What does default constructor here? String=null or String=blue?

If String=Blue,it does by default constructor?

 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Variable "Color" is initialized to blue, because, you've initialised it with the value. But, the variable "name" is initialized to null. It's done by the default constructor.
 
Campbell Ritchie
Marshal
Posts: 55768
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abimaran Kugathasan wrote:. . . the variable "name" is initialized to null. It's done by the default constructor.
Not quite. The default constructor does nothing with any of the fields; they are filled with default values, which in the case of a reference type is null, at the place of declaration.

It is bad practice to have a class with fields and not set them up in the constructor; it allows your object to be in an inconsistent state.When you first buy a car, it is travelling at a speed of 0. It is best to initialise all fields, even to 0 which is the same as the default value.
 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
still not clear for me.

Does default constructor initialize colour to "blue"?
 
Campbell Ritchie
Marshal
Posts: 55768
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
abalfazl hossein wrote: . . . Does default constructor initialize colour to "blue"?
No. Your declaration does that. Look:
you earlier wrote:
. . . and as I said
The default constructor does nothing with any of the fields . . .
The following was inaccurate and misleading:
Abimaran Kugathasan wrote: . . . the variable "name" is initialized to null. It's done by the default constructor.
* * * * *
Why don't you add a print statement and print out the colour and you will see whether it comes out as blue or null.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!