10 Mar 1996

Constructors

An application program can create a new object from any public class using the new operation. However, the program cannot be expected to know how to initialize all the fields of the object. There may be non-public instance variables that can only be set by methods internal to the class itself. Some variables may have interdependencies. If there are references to object of some other class, it may be necessary to internally execute the new operation to allocate objects of these secondary classes. Finally, objects may have implied relationships between operating system resources (files, network sessions, window handles) that require explicit initialization.

For all these reasons, object oriented languages provide a special type of method called a constructor. The name of a constructor is the same as the name of the class in which it is located. Constructors may have arguments that provide values used to initialize a new object of the class.

class Date {

public Date(int newmonth, int newday, int newyear) {…};
};

Once a constructor is defined, it can be called in the new operation that dynamically allocates a new object of the class.

Date Xmas = new Date(12, 25, 1996);

There can be more than one constructor method. All have the same name (the name of the class) but different numbers or types of arguments:

public Date(int newmonth, int newday, int newyear) {…};
public Date(String datestring) {…};

Date Bloomsday = new Date("June 16, 1904");

One constructor can be declared with no arguments. It is the default constructor and is called explicitly when an object is allocated with just "new classname" (no arguments).

One class can be defined by extending another parent class. A constructor for the new subclass will generally call one of the constructors for the parent class to fill in the field variables inherited from the parent class. If the subclass has no constructor, but the parent class has a default constructor (with no arguments) then the Java Interpreter calls the default parent constructor method.

Continue Back PCLT

Copyright 1996 PC Lube and Tune -- Java H. Gilbert

This document generated by SpHyDir, another fine product of PC Lube and Tune.