13
Chapter 3 Constructors 3.0 Introduction Whenever you define a class, a special user defined class type, gets created for use in java codes. Software objects can then be created out of that class type and used in java programs similarly as a conventional data type. When an object is created from a defined class, use of the new operator is made class-name object = new class-name(); where class-name() calls the default constructor for creating an object of class-name type. A constructor determines how an object will be initialized when created. A java programmer may include explicitly one or more constructor (s) while defining a class. If no explicit constructor is specified within a program, Java automatically supplies a default constructor. The initialization of the created object is just carried out either by the default constructor [when no constructor method is defined explicitly in a class] or by one of the programmer’s supplied Constructors. A constructor can be regarded as a special member function whose name will be the same as that of the class being initialized. However, no return type – even void -- is used with that special member function. This is because a constructor always returns an object of the respective class type.

Java Chap3: Constructors (Prof. Ananda M Ghosh.)

Embed Size (px)

DESCRIPTION

Constructors for creation of Objects from a predefined Class in Java language,

Citation preview

Page 1: Java Chap3: Constructors (Prof. Ananda M Ghosh.)

Chapter 3

Constructors

3.0 Introduction

Whenever you define a class, a special user defined class type, gets created for use in java codes. Software objects can then be created out of that class type and used in java programs similarly as a conventional data type.

When an object is created from a defined class, use of the new operator is made

class-name object = new class-name();

where class-name() calls the default constructor for creating an object of class-name type. A constructor determines how an object will be initialized when created.

A java programmer may include explicitly one or more constructor (s) while defining a class. If no explicit constructor is specified within a program, Java automatically supplies a default constructor. The initialization of the created object is just carried out either by the default constructor [when no constructor method is defined explicitly in a class] or by one of the programmer’s supplied Constructors.

A constructor can be regarded as a special member function whose name will be the same as that of the class being initialized. However, no return type – even void -- is used with that special member function. This is because a constructor always returns an object of the respective class type.

This chapter will deal with different aspects of default constructor, constructors with and without any parameters, etc. Constructor Overloading (i.e. use of multiple constructors) is allowed in a class definition – and discussion about them will also be made giving appropriate examples.

3.1 Default Constructor

When a programmer does not specify a constructor explicitly in a class, Java supplies a default constructor for that class. The default constructor always initializes all instant variables with either zero or null value(s).

When a constructor remains defined within a class, the default one is no longer used. For simple classes, default constructors may serve the purpose, but for more efficient and effective initialization, a programmer will have to define his/her own constructor(s) as per application specific requirements.

Page 2: Java Chap3: Constructors (Prof. Ananda M Ghosh.)

Suppose you define a class DefaultCube as shown in example-3.1

Example-3.1 Demo of Default Constructor

// When Class Definition does not contain any constructor method

public class DefaultCube{ // instance variables private int size; int length = size; int width = size; int height = size; /** * No Constructor is specified here * Depending on the Default Constructor */

/** * a method to * display cube volume */ public void volumeMethod() { // codes used in the method int volume = length* width* height; System.out.println("Volume of the default Cube is :" + volume); }}

As there is no constructor specified in the DefaultCube class, the default constructor will initialize the size, length, width, and height with zero values. In BlueJ environment, enter the above class and then compile.

Create an object instance and inspect the values of its instance variables. See that all instance variables are set to zero values (See picture 3.1). Calling the volumeMethod() you get further confirmation because the result of the computed volume is also displayed as zero.

This shows that why initialization with desired values of instant variables of a class is necessary.

We can pass arguments to a constructor method if we make use of Parameterized Constructor(s).

Page 3: Java Chap3: Constructors (Prof. Ananda M Ghosh.)

Picture 3.1

3.2 Parameterized Constructor(s )

We all know that a cube has equal length, width and height. Therefore, just a single value of “size” will be sufficient to determine the volume of a cube. So we can define a class cube with a constructor having a single parameter only. Example-3.2 shows a single parametric constructor for the class Cube.

Example-3.2 Class with a single parameter Constructor

public class Cube{

double width;double height;double depth;

/** Constructor defined With a single parameter */public Cube( double x){ width = x; height =width; length = width; }

/** * a method - computing volume */

Page 4: Java Chap3: Constructors (Prof. Ananda M Ghosh.)

public void volume(){

double vol = width*height*depth;System.out.println ("Volume of the Specified Cube =" + vol);

} }

Carefully observe a few aspects of the defined class Cube (example-3.2):

1) Name of the constructor is same as that of the class.2) Constructor (...) is not specified with any return type although it looks like any

other member function.3) Within parentheses a single parameter -- x of type double -- has been specified.

The value of x will determine the size of the cube.4) The Cube class does not contain any main () method. Therefore, one cube object

is to be created first to execute the program. While creating a cube-object, BlueJ will ask for a value of x with which the

cube size will be initialized.5) Create more cube-objects of different sizes and be familiar with the role of a

constructor in the process of initialization.

It is possible to specify a constructor with multiple parameters. In fact, instead of a cube, if the volume of a solid box with different values of length, width and height is to be found out, we will have to take help of a constructor which will be able to accept three parameters, one each for length, width and height.

3.2.1 Constructor with Multiple Parameters

As mentioned, for initialization of a solid box object – three parametric values, one each for length, width and height, will be required for initialization (picture 3.2). Example-3.3 shows the definition of a SolidBox class with a constructor capable of accepting three parameters.

Example-3.3 An example of a Constructor with Three Parameters

public class SolidBox{double width, height, depth;

/** Constructor for objects of class SolidBox With three parameters */public SolidBox( double w, double h, double l)

Page 5: Java Chap3: Constructors (Prof. Ananda M Ghosh.)

{ width =w; height =h; length =l;

}

/** * a method - to compute volume */public void volumeSBox(){double vol = width*height* length;System.out.println(" Volume of the Solid Box = " + vol);

}

}

Picture 3.2

Enter values and run these java programs to satisfy yourself.

Page 6: Java Chap3: Constructors (Prof. Ananda M Ghosh.)

3.3 Overloading Constructors

Let us first try to understand what “overloading” means. In a java program it is possible to have two or more methods or functions using the same name provided each one is having different parameter(s) declaration. In such cases, methods or functions are said to be overloaded. Method or function overloading is one of the ways of implementing polymorphism in OOP languages.

Like methods, constructors can also be overloaded. That means, a class can have more than one constructor (using the same name as that of the class) but each one should have different parametric declarations.

Such constructor overloading can help object initialization with different values under different situations. Let us look at an example of overloading constructors.

Suppose you want to define a class Solid3D, which can be initialized either as a Cube-object, or as a solid object of any length, width and height. For that we have to define two separate constructors for the class Solid3D.

Example-3.4 Defining a Class Solid3D with two Constructors

public class Solid3D{ // instance variables double length; double width; double height;

/** * Constructor for objects of class Solid3D */

public Solid3D(double size) // First Constructor for Cubes { // initialise instance variables with the value you pass length = size; width = size; height = size; } public Solid3D(double l, double w, double h) // Second Constructor for Solids { length = l; width = w; height = h; }

Page 7: Java Chap3: Constructors (Prof. Ananda M Ghosh.)

/** * An example of a method -- * compute of volume */ public double volMethod() { return length*width*height ; }}

The class Solid3D will be able to create two different types of objects – one type as cubes and another type as a solid of any dimensions. For cubes, only one parameter is to be passed, whereas for any size solid – three parameters are to be passed for initialization.

A controlling DemoSolid class with a main () method can now utilize this Solid3D class, defined with two constructors. DemoSolid will be able to create different category of objects having any desired dimensions and will compute and display their respective volumes as shown in example-3.5.

Example 3.5 DemoSolid class utilizing the Overloading Constructors of the Solid3D class

public class DemoSolid

{ public static void main() { double length; double width; double height; double vol1, vol2; Solid3D cube = new Solid3D(8.0); // cube object instantiated

Solid3D solidx = new Solid3D(10.0,5.0, 8.0); // variable size solid object // instantiated

vol1 = cube.volMethod(); System.out.println(" Volume of the Cube is :" + vol1); vol2 = solidx.volMethod(); System.out.println(" Volume of the solid is :" + vol2); } } // The results appear on the Terminal Window shown below (Picture 3.3)

Page 8: Java Chap3: Constructors (Prof. Ananda M Ghosh.)

Example 3.5 shows how multiple constructors can help a java programmer to take care of different application requirements. This example also tells about the association of more than one classes and the importance of the class with the main () method.

3.4 Concept of Destructor & Garbage Collection

In object oriented programming there is a destructor concept. Destructor is a function, which is called to destroy any created object lying unused. Destruction means removing an object from the main memory space.

The new operator creates objects by taking help of the constructor(s), but by which function those objects are to be destroyed and the occupied memory space can be released for run-time reallocation is another important question. A destructor function can take care of that release operation. A destructor function (not used in java but used by C++) can be specified as

~ class-name(). // Not constructor (as constructor gets its class-name)

A destructor cannot accept any argument. Being a function, it obeys the usual access rules. Sometimes an object may need to perform some action(s) before it gets destroyed. To handle such situations, java provides a mechanism called finalization. A finalizer can be added within a class by using a finalize () method.

The finalize() method has the general form :--

protected void finalize(){ // finalization codes }

The protected keyword prevents access to finalize function by the external codes. The java run time is only allowed to call that method whenever object destruction with finalization is needed.

Java’s system takes care of unused objects to free memory space automatically as and when needed. This technique of automatic destruction of objects is known as garbage collection. Thus a java programmer is made free from the burden of destroying unused objects explicitly. Of course, C++ programmers will have to make use of destructor(s) explicitly.

Picture 3.3 Outputs of example-3.5

Page 9: Java Chap3: Constructors (Prof. Ananda M Ghosh.)

3.5 Conclusions

This chapter has explained the importance of constructors in a class definition. It shows how a constructor can be specified like a method or function having the same name as that of the class. Constructor method does not make use of any return-type.

A class definition without user-defined constructor is possible. In that case, default constructors, which initializes instance variables with zero or null values, comes into action automatically.

The importance of parameterized constructors is also explained showing appropriate examples. The concept of constructor overloading and its use in a class has also been explained with examples. The importance of multiple constructors has also been demonstrated.

The destructor concept has been explained briefly. In Java, destruction process is taken care of by the system’s garbage collector. The importance of finalizes () function is also made clear.