Java Programming For Noobies - Banner

---
Read First
---
Introduction
Java Keywords
Constructors
Class
Class Structure
Fields
Methods
Program block delimeters
Comments

---
Data Types
---
Primitive Types
Integer Data Type
Byte
Short
Integer
Long
Boolean

Basic Java



Constructors

Constructors, are a special kind of method, which primarily perform initialization tasks for an object. They are implicitly called upon the instantiation of a new object for any given class. Put simply, the purpose of a constructor is to do whatever is neccessary to initialize an object.

Constructors have two special features:

  1. Firstly a constructor does not declare a return data type or ‘void’ like other methods do.


  2. And secondly a constructor’s name is always the same as the name of the class.

Call Your Parents!

It is worth remembering that if you define a class without a constructor then Java will automatically put in a default constructor for you.

Screenshot - showing how Java creates a default constructor if one has not been defined.

All that the constructor above does is call the parent's class constructor. Since all classes must be the child of some class, (with the notable exception of java.lang.object, which is the parent of all classes), this call is always legal

In fact, any constructor you create must have as it's first action a call to some other constructor. Java uses the class's parent's constructor as default. You can specify this call explicity, or if you don't, Java inserts one for you. The following code will illustrate for you the point:

 Screenshot - showing constructors working.

Since the call to the Parent's constructor happens, whether you like it or not, the output from instantiating a child object would be

Parent
Child


Java insists that every constructor must call another constructor as its first action; if you don't specify one, it uses the parents default (no parameters) constructor. If you do specify a different constructor to be called (as the first statement of your constructor), you will have appeased Java and it will not perform the default call to the parents constructor.


Return to Previous Page

Get Java @ Sun Microsystems Get NetBeans 5.5 - All the tools software developers need to create cross-platform Java desktop, enterprise and web applications
Return to the Home page© Copyright to Java Programming For Noobies - Home - Basic Java - Advanced Java - News - Articles - Contact Us -