www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons The Constructor Function Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
As in C++, constructor functions in Java are used to initialize the instances of a class. They have no return type (not even void) and can be overloaded. You can have multiple constructor functions, each with different numbers and / or types of arguments. If you don't write any constructor functions, a default (no-argument) constructor (that doesn't do anything) will be supplied by the compiler.

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

Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.