![]() |
|
The Constructor Function in Java, Free online Core Java Programming Tutorial, Learn Java Programming Language online for free... |
| Lessons | The Constructor Function |
|
|
If you write a constructor that takes one or more arguments, no default constructor will be supplied and therefore, an attempt to create a new object without passing any arguments will cause a compile-time error. It is often useful to have one constructor call another. For example, a constructor with no arguments might call a constructor with one argument, passing a default value. This call must be the first statement in the constructor. It is performed using this as if it were the name of the method. For example: this( 10 ); The above is a call to a constructor that expects one integer argument. Initialization of fields: If you don't initialize a field i.e. either you don't write any constructor function, or your constructor function just doesn't assign a value to that field, the field will be given a default value, depending on its type. The default values of different types of variables have been discussed in a previous lesson.
Next >>> Lesson No. 8: Java Access Specifiers
|